Tkinter button commands with lambda in Python

ive tried to find a solution, but could not find the one that works. I have a 2d list of tkinter buttons, and I want to change their text when I click. I tried to do this:

def create_board(number): print(number) for i in range (0,number): buttonList.append([]) for j in range(0,number): print(i,j) buttonList[i].append(Button(root, text = " ", command = lambda: update_binary_text(i,j))) buttonList[i][j].pack() 

Then, when it is clicked, it calls this function:

 def update_binary_text(first,second): print(first,second) buttonList[first][second]["text"] = "1" 

When I press the button, it just doesn’t do anything, I had a program showing the indices of the button the button was pressed on and they ALL show 4, 4 (this is when the number of variables = 5) Is there a solution for this?
this is my first python attempt for a class.

thanks

+6
source share
2 answers

You can fix this problem by creating a closure for i and j with creating each lambda:

 command = lambda i=i, j=j: update_binary_text(i, j) 

You can also create a factory callback with links 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) 
+8
source

Whenever I need a set of similar widgets, I find it easiest to wrap them in an object and pass the associated method as a callback, rather than playing tricks with a lambda. So, instead of 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 of buttonList[] these objects, and not the widgets themselves. To update the text, either provide a method for this, or directly contact the member: buttonList[i].button.configure(. . .) And when the callback is activated, it has the whole object and any attributes that you may need in self .

0
source

Source: https://habr.com/ru/post/943658/


All Articles