如何确定在Tkinter中按下了哪个按钮?

10 投票
2 回答
15742 浏览
提问于 2025-04-15 14:55

我正在学习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 个回答

2

看起来这个命令方法没有接收到任何事件对象。

我能想到两种解决办法:

  • 给每个按钮关联一个独特的回调函数

  • button.bind('<Button-1>', self.populateMethod) 来替代直接把 self.populateMethod 作为 command 传入。这样的话,self.populateMethod 需要接受一个第二个参数,这个参数就是事件对象。

    假设这个第二个参数叫 event,那么 event.widget 就是指向被点击的按钮。

24

你可以使用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})

撰写回答