2

I have a Tkinter GUI in which, if a button is clicked, its text gets changed to a corresponding item in a list matches.

The list matches and list buttons are not known yet. My code looks something like this:

#Defining the buttons
buttons = []
for i in range(len(matches)):
    buttons.append(Button(my_frame, text = " ", 
        font = ("Helvetica", 20), height = 1, width = 1,
        command = lambda: change(i)))


def change(index):
    if buttons[index]['text'] == matches[i]:
        buttons[index]['text'] = " "
    else:
        buttons[index]['text'] = matches[i]

Whichever button I press, the text changes only for the last button. How do I fix this?

0

1 Answer 1

2

That's because of lambda's late bindings

To avoid that, use functools.partial instead of command = lambda: change(i)))

import functools 

buttons = []
for i in range(len(matches)):
    buttons.append(
        Button(
            my_frame,
            text=" ",
            font=("Helvetica", 20),
            height=1,
            width=1,
            command=functools.partial(change, i)
        )
    )

Another simpler option is to replace

command = lambda: change(i)))

with

command = lambda i=i: change(i)))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.