繁体   English   中英

为什么它说“条目”没有定义?

[英]Why does it say that 'entry' is not 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()

这是因为变量entry是在单独的 function 中定义的,然后在您调用它的位置。 有两种方法可以解决此问题。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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