为什么说'entry'没有定义?

Why does it say that 'entry' is not defined?

每次我 运行 这个,输入一些东西,然后点击按钮,它说“名称 'entry' 未定义”。为什么?我以为 'entry' 被定义了。

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


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