Daniel Lacey
Daniel Lacey

Reputation: 1

How do i get .configure to work in a for loop

I'm trying to write some code which allows me to press a button, then the background of that button will change. the code I've written only changes the colour of the final button when any of the other buttons are pressed. can someone help me resolve this?

import tkinter as tk

column = 0
                   
def click_me():
    button.configure(bg='red')

for i in range(10):
    button = tk.Button(text="___", font='Fixedsys 20 bold', command=click_me)
    button.grid(column=column, row=0)
    column += 1

Upvotes: 0

Views: 30

Answers (1)

TheLizzard
TheLizzard

Reputation: 7700

Try this:

import tkinter as tk
from functools import partial


column = 0

def click_me(button):
    button.configure(bg="red")

for i in range(10):
    button = tk.Button(text="Button %i" % i, font="Fixedsys 20 bold")
    # Create the command
    command = partial(click_me, button)
    button.config(command=command)
    button.grid(column=column, row=0)
    column += 1

I passed in the button as a parameter to the function. For more info on how to use partial read this.

Upvotes: 1

Related Questions