Reputation: 15
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()
Upvotes: 0
Views: 508
Reputation: 855
This is because the varible entry
was defined in a seperate function, then where you called it. There are two ways to fix this.
a) Use global variables
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
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()
Upvotes: 1