每次我运行这个,输入一些东西,然后点击按钮,它说“名称'条目'未定义”。为什么?我认为“条目”已定义。
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
是在一个单独的函数中定义的,然后是你调用它的地方。有两种方法可以解决这个问题。
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 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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句