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

Syd*_*ius 9 python tkinter button

我在学习Python的同时做了一个简单的小工具.它动态生成按钮列表:

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

那部分工作正常.但是,我需要知道里面按了哪个按钮self.populateMethod.关于我怎么能说出来的任何建议?

Bry*_*ley 17

您可以使用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})
Run Code Online (Sandbox Code Playgroud)