【问题标题】:Python: Assign commnds to buttons using a for loop when using TkinterPython:使用 Tkinter 时使用 for 循环将命令分配给按钮
【发布时间】:2012-06-20 22:57:32
【问题描述】:

我正在使用 Tkinter,我想知道是否有一种方法可以为一堆按钮命令定义一个回调函数,其中命令的名称类似于“callback1”、“callback2”等。

我正在创建这样的按钮(它是日历的一部分):

buttonlist = ['c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7']
daylist = ['mo', 'tu', 'we', 'th', 'fr', 'sa', 'su']
counter = 0
daycount = -1

for item in buttonlist:
    counter = counter + 1
    daycount = daycount + 1
    item = Tkinter.Button(label1, width=5, bg = 'white', 
                                text = daylist[daycount])
    item.grid(row=0, column = counter, padx=5, pady=5)

我可以手动为每个按钮添加一个命令,并为每个按钮定义一个函数,但我宁愿只定义一个函数,并在 for 循环中为命令指定唯一名称,因为我也有一个按钮每个月的每一天。

有没有办法做到这一点? 我正在使用 Python 2.7.2

谢谢

【问题讨论】:

    标签: python button tkinter


    【解决方案1】:

    很久没用Tkinter了

    首先,您可以将循环修改为(根据需要进行调整):

    for idx, (bl, dl) in enumerate(zip(buttonlist, daylist)):
        TKinter.Button(text=dl, command=lambda: button_pressed(bl))
    

    然后放在合适的地方:

    def button_pressed(which):
        print 'I am button {}'.format(b1)
    

    lambda 函数创建一个匿名函数,其工作是使用按下的按钮调用 button_pressed 函数(如果这有意义的话!)

    【讨论】:

    • 谢谢!还没有完全弄清楚如何让它工作,但现在我知道从哪里开始了。非常感谢。
    猜你喜欢
    • 2022-01-06
    • 2016-11-30
    • 2020-05-19
    相关资源
    最近更新 更多