tkinter button commands with lambda in Python
You can fix this problem by creating a closure for i
and j
with the creation of each lambda:
command = lambda i=i, j=j: update_binary_text(i, j)
You could also create a callback factory with references to the button objects themselves:
def callback_factory(button): return lambda: button["text"] = "1"
And then in your initialization code:
for j in range(0, number): new_button = Button(root, text=" ") new_button.configure(command=callback_factory(new_button)) new_button.pack() buttonList.append(new_button)
Whenever I need a collection of similar widgets, I find it's simplest to enclose them in an object and pass a bound-method as callback rather than playing tricks with lambda. So, instead of having a list like buttonList[]
with widgets, create an object:
class MyButton(object): def __init__(self, i, j): self.i = i self.j = j self.button = Button(..., command = self.callback) def callback(self): . . .
Now, you have a list buttonList[]
of these objects, rather than the widgets themselves. To update the text, either provide a method for that, or else access the member directly: buttonList[i].button.configure(. . .)
And when the callback is activated, it has the entire object and whatever attributes you might need in self
.