避免在tkinter中两次单击按钮时标签两次显示两次

时间:2020-06-22 12:25:52

标签: python tkinter

我正在进行数学测验,并且正在尝试进行错误处理。我希望仅在先前显示标签self.wrongnum.destroy()的情况下调用wrongnum。现在发生的事情是,如果我单击两次按钮(如果用户输入的值有问题,它将显示标签wrongnum),标签也将一个接一个显示,但只有一个标签被破坏。如何避免出现同一标签中的2个?或者我该如何消灭两者?

下面是我的代码,如果我的编写方式还有其他问题,也请告诉我。谢谢

    def q2(self, master):
        randomiser()
        global answer
        self.master = master
        self.frame = Frame(master, padx=200, pady=200)
        self.frame.grid()
        self.user_choice = StringVar()
        self.user_choice.set("")
        self.q = Label(self.frame, text="What is {} x {} ?".format(x, y))
        self.q.grid(row=0)
        self.ans = Entry(self.frame, width=50, textvariable=self.user_choice)
        self.ans.grid(row=1)
        answer = x*y
        self.sub = Button(self.frame, text="submit", command=lambda:[self.check(), randomiser()])
        self.sub.grid(row=3)

    def check(self):
        try:
            if self.user_choice == None:
                self.wrongnum = Label(self.frame, text="Please enter a number")
                self.wrongnum.grid(row=5)
                self.necs()
            else:
                self.correct()
        except ValueError:
            self.wrongnum = Label(self.frame, text="Please enter a number")
            self.wrongnum.grid(row=5)

    def correct(self):
        global p
        if int(self.user_choice.get()) == answer:
            cor = Label(self.frame,text="Correct!")
            cor.grid(row=5, pady=20)
            p += 1
            self.sub.destroy()
            self.wrongnum.destroy() 
            nex = Button(self.frame, text="Next", command=self.necs)
            nex.grid(row=4)
        else:
            inc = Label(self.frame,text="incorrect, the correct answer is {}".format(answer))
            inc.grid(row=5, pady=20)
            self.sub.destroy()
            nex = Button(self.frame, text="Next", command=self.necs)
            nex.grid(row=4)

0 个答案:

没有答案