Python tkinter : Problems when dynamically creating a button and connecting the event handler for each button using Lambda.

Asked 2 years ago, Updated 2 years ago, 105 views


i = 0
for f in range(len(machh)): 
    globals()['button{}'.format(f)] = 
        tkinter.Button(frame, 
                       command = lambda : self.Match_Deep_Search(f) )
    # Create buttons as large as the list 

def Match_Deep_Search(mId):
        print(mId)

The list called machh contains the full history of a particular user. If you played 10 games, there are 10 id's on the list.

If you create a button as big as the size of the Mach list with the for door and press the button according to the order, I want the id of this order to be included as a Match_Deep_Search function

(Press the 1st button to enter the function with the 1st id as a parameter)

If you use f as a parameter, the number is fixed to the size of the final f.

In this case, I think you need to know which button you are, so how can you implement it? Please reply.

python algorithm tkinter lambda

2022-09-20 16:54

2 Answers


from tkinter import Button, Tk


class MainWin(Tk):
    def __init__(self, parent):
        Tk.__init__(self, parent)
        self.parent = parent
        self.buttons = {}
        self.dat = ["A", "B", "C", "D"]
        self.init_widgets()

    def init_widgets(self):
        for i, d in enumerate(self.dat):
            btn = Button(
                self,
                width=10,
                text=f"{i}-{d}",
                command=lambda x=i: self.on_click(x),
            )
            btn.grid(row=i, column=0)
            self.buttons[i] = btn

    def on_click(self, i):
        print(f"{i} clicked")


if __name__ == "__main__":
    app = MainWin(None)
    app.mainloop()

lambdax=i:self.on_clilck(x) It works as you want when you specify other variables in the lambda function.

Using global() to dynamically generate button variables is not good. It's much better to make it a dictionary (or list) as in my example, and to manage it by putting the generated buttons in it. You can see how many buttons there are in no time, and so on. If you're using globals() to create a variable, you're doing it wrong.


2022-09-20 16:54

I don't know what it means to be fixed to the size of f.

I wish there was an example. If the code indicates that the 4th recording is selected, the Match_Deep_Search(mId) function will output the number 4, not the mach list element.

I think we should put a list element, not a number, in the variable as follows.

i = 3
for f in range(len(machh)): 
    if i == f:
        globals()['button{}'.format(f)] = tkinter.Button(frame, command = lambda : self.Match_Deep_Search(machh[f]) )
    # Create buttons as large as the list 
def Match_Deep_Search(mId):
        print(mId)


2022-09-20 16:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.