2009-10-08 63 views
8

我在學習Python時做了一個簡單的小工具。它動態生成一個按鈕列表:確定在Tkinter中按下哪個按鈕?

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中哪些按鈕被按下。有關我如何能夠告訴的任何建議?

回答

15

您可以使用拉姆達傳遞參數給一個命令:

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}) 
1

看來,該命令方法沒有傳遞任何事件對象。

我能想到的兩種解決方法的:

  • 聯想獨特的回調,每個按鈕

  • 呼叫button.bind('<Button-1>', self.populateMethod)強似self.populateMethod爲command的。然後self.populateMethod必須接受第二個參數,它將是一個事件對象。

    假設第二個參數被稱爲eventevent.widget是對被點擊的按鈕的引用。

+0

我做了第二種方法,它似乎做我想做的。謝謝! – Sydius 2009-10-08 20:01:03

+0

如果您使用'bind'而不是利用內置的'command'屬性,那麼您將無法使用Tkinter的內置功能來導航並使用鍵盤單擊按鈕。當然,你可以應用一堆綁定來處理所有的特殊情況,但使用'command'屬性更容易。 – 2012-06-07 18:40:35

+0

@BryanOakley:確實;你使用lambdas的建議更清潔。 – 2012-06-08 18:50:52