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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1539787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:32:02  来源:igfitidea点击:

Determine which Button was pressed in Tkinter?

pythonbuttontkinter

提问by Sydius

I'm making a simple little utility while learning Python. It dynamically generates a list of buttons:

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

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

That part works fine. However, I need to know which of the buttons was pressed inside self.populateMethod. Any advice on how I might be able to tell?

那部分工作正常。但是,我需要知道里面按下了哪个按钮self.populateMethod。关于我如何分辨的任何建议?

回答by Bryan Oakley

You can use lambda to pass arguments to a command:

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

回答by Rapha?l Saint-Pierre

It seems that the command method is not passed any event object.

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

I can think of two workarounds:

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

  • associate a unique callback to each button

  • call button.bind('<Button-1>', self.populateMethod)instead of passing self.populateMethod as command. self.populateMethod must then accept a second argument which will be an event object.

    Assuming that this second argument is called event, event.widgetis a reference to the button that was clicked.

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

  • 调用button.bind('<Button-1>', self.populateMethod)而不是将 self.populateMethod 作为command. self.populateMethod 然后必须接受将是事件对象的第二个参数。

    假设第二个参数被称为eventevent.widget是对被点击按钮的引用。