2015-09-28 135 views
0

我正在使用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

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

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) 
相关问题