Tkinter: creating an arbitrary number of buttons/widgets

前端 未结 2 421
悲&欢浪女
悲&欢浪女 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?

    0 讨论(0)
  • 2021-01-23 08:03

    You can store Buttons in a list:

    from tkinter import *
    master = Tk()
    buttons = []
    n = 10
    for i in range(n):
        button = Button(master, text = str(i))
        button.pack()
        buttons.append(button)
    master.mainloop()
    
    0 讨论(0)
提交回复
热议问题