【问题标题】:Is it possible to know the button name through function是否可以通过函数知道按钮名称
【发布时间】:2015-09-28 06:20:11
【问题描述】:

我正在使用 20 个按钮,当单击任何一个按钮时,我正在调用“btn_click”函数。是否可以通过该函数知道按钮名称(按下哪个按钮)。请查找代码 sn-p下面。

    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) 

【问题讨论】:

    标签: python-2.7 button tkinter


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-22
      • 2013-07-14
      • 2022-01-22
      • 2014-09-08
      • 2015-07-28
      • 2020-11-28
      相关资源
      最近更新 更多