【问题标题】:Why does it say that 'entry' is not defined?为什么它说“条目”没有定义?
【发布时间】:2021-04-23 15:25:30
【问题描述】:

每次我运行它时,输入一些内容,然后单击按钮,它会显示“名称'条目'未定义”。为什么?我认为“入口”已定义。

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是一个局部变量,只在main内部可见。
  • 那么我该怎么做才能使变量在 main 之外工作
  • 在函数内部使用global entry
  • 你能告诉我怎么做吗?我是新手
  • 您可以 a) 使用全局变量或 b) 使用类。我的答案中的代码:)

标签: python tkinter undefined


【解决方案1】:

这是因为变量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()

【讨论】:

    猜你喜欢
    • 2016-09-27
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2017-08-29
    • 2018-08-21
    • 1970-01-01
    相关资源
    最近更新 更多