Tkinter: creating an arbitrary number of buttons/widgets

前端 未结 2 424
悲&欢浪女
悲&欢浪女 2021-01-23 07:54

So, I\'ve got a list with entries that look like this:

Option1  Placeholder1    2   Placeholder2    0      
Option2  Placeholder1    4              
Option3  Pla         


        
2条回答
  •  爱一瞬间的悲伤
    2021-01-23 08:00

    Figured it out! Creating the widgets dynamically with a dictionary worked just fine, but calling the correct widget on the various button presses was more difficult. This is what I had:

    buttons = dict()
    for k in range(len(info)):
        buttons[k] = Button(top, text=info[k], command=lambda: my_function(buttons[k]))
    

    ... which would work, but all button presses would call the function with the last created button as the target. All that was needed was a few extra characters in the command part of the buttons:

    buttons = dict()
    for k in range(len(info)):
        buttons[k] = Button(top, text=info[k], command=lambda a=k: my_function(buttons[a]))
    

    ... which I assume works because it somehow stores the value of k inside a rather than taking the last known value of k, i.e. equivalent to the last created button. Is this correct?

提交回复
热议问题