是否可以通过功能知道按钮名称

时间:2015-09-28 06:20:11

标签: python-2.7 button tkinter

我正在使用20个按钮,当点击任何一个按钮时,我正在调用“btn_click”功能。是否可以通过该功能知道按钮名称(按下哪个按钮)。请查看下面的代码片段。

    t=['one','two','three','four','five','six','seven','untill to twenty']
    for i in range(1,20):
         obj=Button(root1,text=t[i],command=btn_click,width=27)
         obj.grid(row=i,column=0,sticky=W,padx=15,pady=15) 

1 个答案:

答案 0 :(得分:1)

您可以将按钮名称作为参数传递给回调函数。

def btn_click(button_name):
    print button_name

然后你可以创建一个lambda,将当前名称传递给回调。

t = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'untill to twenty']
for i, x in enumerate(t):
     obj = Button(root1, text=x, command=lambda name=x: btn_click(name), width=27)
     obj.grid(row=i, column=0, sticky=W, padx=15, pady=15) 

但请注意lambda can behave unexpectedly when used inside a loop,因此name=x默认参数。或者改为使用functools.partial

     obj = Button(root1, text=x, command=functools.partial(btn_click, x), width=27)
相关问题