2012-06-20 51 views
1

我正在使用Tkinter,我想知道是否有一种方法可以为一堆按钮命令定义一个回调函数,其中命令的名称类似于“调用callback1”,callback2' 等Python:使用Tkinter时使用for循环分配通讯按钮使用Tkinter

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

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

感谢

回答

2

,因为我用的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函数(如果这样做合理)

+0

Thanks!还没有弄清楚如何使它工作,但现在我知道从哪里开始。非常感激。 – Yngve