Home > Back-end >  Function not changing with for-loop python
Function not changing with for-loop python

Time:04-02

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?

CodePudding user response:

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)))

  • Related