简体   繁体   中英

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. 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM