[英]Why does it say that 'entry' is not defined?
每次我運行它時,輸入一些內容,然后單擊按鈕,它會顯示“名稱'條目'未定義”。 為什么? 我認為“進入”已被定義。
def displayText():
textToDisplay=entry.get()
label.config(text=textToDisplay)
def main():
import tkinter as tk
window=tk.Tk()
label=tk.Label(master=window, text="When you press the button below, whatever is in the text box will be displayed here")
label.pack()
entry=tk.Entry(width=10, bg="white", fg="black")
entry.pack()
button=tk.Button(text="Click", width=10, command=displayText)
button.pack()
entry.insert(0, "")
window.mainloop()
sys.exit(0)
if(__name__=="__main__"):
main()
這是因為變量entry
是在單獨的 function 中定義的,然后在您調用它的位置。 有兩種方法可以解決此問題。
a) 使用全局變量
def displayText():
textToDisplay=entry.get()
label.config(text=textToDisplay)
def main():
import tkinter as tk
global entry, label
window=tk.Tk()
label=tk.Label(master=window, text="When you press the button below, whatever is in the text box will be displayed here")
label.pack()
entry=tk.Entry(width=10, bg="white", fg="black")
entry.pack()
button=tk.Button(text="Click", width=10, command=displayText)
button.pack()
entry.insert(0, "")
window.mainloop()
sys.exit(0)
if(__name__=="__main__"):
main()
b) 使用 class
class GUI:
def __init__(self):
self.main()
def displayText(self):
textToDisplay=self.entry.get()
self.label.config(text=textToDisplay)
def main(self):
import tkinter as tk
window=tk.Tk()
self.label=tk.Label(master=window, text="When you press the button below, whatever is in the text box will be displayed here")
self.label.pack()
self.entry=tk.Entry(width=10, bg="white", fg="black")
self.entry.pack()
button=tk.Button(text="Click", width=10, command=self.displayText)
button.pack()
self.entry.insert(0, "")
window.mainloop()
sys.exit(0)
if(__name__=="__main__"):
GUI()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.