[英]Functions in Tkinter
所以我正在練習將Tkinter與python結合使用,而我只是想學習基礎知識。 我現在的代碼是
import Tkinter as tk
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.prompt = tk.Label(self, text="Press a button", anchor="w")
self.button1 = tk.Button(self, text="Button 1", command = self.button1)
self.button2 = tk.Button(self, text="Button 2", command = self.button2)
self.output = tk.Label(self, text="")
# lay the widgets out on the screen.
self.prompt.pack(side="top", fill="x")
self.output.pack(side="top", fill="x", expand=True)
self.button1.pack(side="left")
self.button2.pack(side="right")
def button1(self):
result = "You just pressed button 1."
self.output.configure(text=result)
def button2(self):
result = "You just pressed button 2."
self.output.configure(text=result)
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
這可以正常工作,但我正在嘗試使其更簡潔一點,並且僅使用一個功能。 我嘗試了這個:
def button(self, string):
result = string
self.output.configure(text=result)
在按鈕上,我使用了
self.button1 = tk.Button(self, text="Button 1", command = self.button(
"You just pressed button 1"))
self.button2 = tk.Button(self, text="Button 2", command = self.button(
"You just pressed button 2"))
但是由於某種原因,當我將第二個參數添加到按鈕函數時,它停止工作。 如果我使用完全相同的代碼,則可以正常工作,但是當我添加第二個參數時,出現此錯誤:
line 31, in button
self.output.configure(text=result)
AttributeError: Example instance has no attribute 'output'
問題是什么?
問題在於command
屬性需要對函數的引用。 當執行command=self.button(...)
,您將立即調用該函數,然后將函數的結果用作command
屬性的值。
如果要傳遞參數,則需要使用lambda
或functools.partial
。 這個問題在這個網站上已經問過很多遍了。 例如,參見使用“ command”和“ bind”上的參數調用函數以及python Tkinter:將參數傳遞給函數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.