[英]Why does it say that 'entry' is not defined?
Every time I run this, type something, and then click the button, it says "name 'entry' is not defined".每次我运行它时,输入一些内容,然后单击按钮,它会显示“名称'条目'未定义”。 Why?为什么? I thought 'entry' was 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()
This is because the varible entry
was defined in a seperate function, then where you called it.这是因为变量entry
是在单独的 function 中定义的,然后在您调用它的位置。 There are two ways to fix this.有两种方法可以解决此问题。
a) Use global variables 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) Use a class 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.