python - 在 python 上定义命令时出现名称错误

标签 python python-3.x tkinter nameerror

我不明白为什么我不断收到错误:NameError:名称“submit_answer”未定义。

class Add(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, background="blue")
        button = tk.Button(self, text="Main Menu", font=LARGE_FONT, background="white",
                           command=lambda: controller.show_frame(Main))
        button.place(relx=0.83, rely=0.92)

        button4 = tk.Button(self, text="Start Game", font=LARGE_FONT, background="white",
                           command=self.time_start)
        button4.place(relx=0.42, rely=0.8, relheight=0.1, relwidth=0.2)

    def time_start(self):
        timelabel = tk.Label(self, text="Good luck!", font=LARGE_FONT, background="blue")
        timelabel.place(relx=0.42, rely=0.8, relheight=0.1, relwidth=0.2)

        x = int(random.uniform(1,10))
        y = int(random.uniform(50,100))
        z = int(random.uniform(10,50))
        qlabel = tk.Label(self, text= (x,"+",y,"+",z,"=",), font=LARGE_FONT, bg="blue")
        qlabel.pack()

##        entrylabel = tk.Label(self, text="Answer:", font=LARGE_FONT, background="blue")
##        entrylabel.pack()

        e1 = tk.Entry(self)
        e1.pack()

        ebutton = tk.Button(self, text="Done", font=LARGE_FONT, background="white",
                            command=submit_answer)
        ebutton.pack()

    def submit_answer(self):
        a = (x+y+z)
        if int(e1.get()) == a:
            answerlabel = tk.Label(self, text="Correct!", font=LARGE_FONT, background="blue")
            answerlable.pack()
        else:
            answerlabel = tk.Label(self, text="Incorrect!", font=LARGE_FONT, background="blue")
            answerlable.pack()

        self.label = tk.Label(self, text="", width=10, font=LARGE_FONT)
        self.label.place(relx=0.1, rely=0.1)
        self.remaining = 0
        self.countdown(5)

最佳答案

为了调用类中的方法submit_answer,您应该使用:self.submit_answer

所以这一行应该更改为:

ebutton = tk.Button(self, text="Done", font=LARGE_FONT, background="white",
                        command=self.submit_answer)

关于python - 在 python 上定义命令时出现名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33724910/

相关文章:

python - 从字典更新多个标签

python - Celery导入库后找不到周期性任务

Python语法: Could colons be optional when at end of line?

Python pickle 不是一对一的 : different pickles give same object

python-3.x - 使用 Python asyncio 从同步函数中运行并等待异步函数

python - tkinter 的 filedialog 中的 (initialdir) 不适用于变量

Python ':.' 的名称是什么,或者是什么搜索词来显示它的含义

python - 使用不相等的值列表创建 Pandas 数据框

python - 如何使用 tkinter 将按钮移出他的 parent ?

python - Tkinter create_image() 保留 PNG 透明度,但 Button(image) 不保留