代码之家  ›  专栏  ›  技术社区  ›  Sydius

确定在tkinter中按下了哪个按钮?

  •  10
  • Sydius  · 技术社区  · 16 年前

    在学习Python时,我正在制作一个简单的小实用程序。它动态生成按钮列表:

    for method in methods:
        button = Button(self.methodFrame, text=method, command=self.populateMethod)
        button.pack({'fill': 'x', 'expand': 1, 'padx': 5, 'pady': 3})
    

    那部分工作得很好。但是,我需要知道里面按了哪个按钮 self.populateMethod . 有什么建议可以告诉我吗?

    2 回复  |  直到 8 年前
        1
  •  18
  •   SilentGhost    16 年前

    可以使用lambda将参数传递给命令:

    def populateMethod(self, method):
        print "method:", method
    
    for method in ["one","two","three"]:
        button = Button(self.methodFrame, text=method, 
            command=lambda m=method: self.populateMethod(m))
        button.pack({'fill': 'x', 'expand': 1, 'padx': 5, 'pady': 3})
    
        2
  •  2
  •   Raphaël Saint-Pierre    16 年前

    似乎命令方法没有传递任何事件对象。

    我可以想到两种解决方法:

    • 将唯一的回调与每个按钮关联

    • 呼叫 button.bind('<Button-1>', self.populateMethod) 而不是传递自我。PopulateMethod为 command . Self.PopulateMethod随后必须接受第二个将成为事件对象的参数。

      假设第二个参数被调用 event , event.widget 是对已单击按钮的引用。