下面的代码是我试图在python上创建的数学测验游戏的“添加”部分。每当点击button4(使用submit_answer命令)时,倒计时秒似乎比以前快两倍。有没有办法让每次点击按钮4时倒计时时间长度保持不变?
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)
self.button4 = tk.Button(self, text="Start Game", font=LARGE_FONT, background="white",
command=self.time_start)
self.button4.place(relx=0.4, rely=0.8, relheight=0.1, relwidth=0.2)
def time_start(self):
self.button4.destroy()
self.x = int(random.uniform(1,10))
self.y = int(random.uniform(50,100))
self.z = int(random.uniform(10,50))
print(self.x+self.y+self.z)
self.qlabel = tk.Label(self, text= (self.x,"+",self.y,"+",self.z,"=",), font=WORD_FONT, bg="blue")
self.qlabel.place(relx=0.25, rely=0.3, relheight=0.05, relwidth=0.3)
self.e1 = tk.Entry(self)
self.e1.place(relx=0.5, rely=0.3, relheight=0.05, relwidth=0.2)
self.ebutton = tk.Button(self, text="Done", font=TITLE_FONT, background="white",
command=self.submit_answer)
self.ebutton.place(relx=0.35, rely=0.5, relheight=0.2, relwidth=0.3)
self.label = tk.Label(self, text="", width=10, font=LARGE_FONT, bg="white")
self.label.place(relx=0.1, rely=0.1)
self.remaining = 0
self.countdown(10)
def submit_answer(self):
a = (self.x+self.y+self.z)
if int(self.e1.get()) == a:
answerlabel = tk.Label(self, text="Correct!", font=LARGE_FONT, background="blue")
answerlabel.pack()
self.label.destroy()
self.qlabel.destroy()
self.e1.destroy()
self.ebutton.destroy()
self.time_start()
else:
answerlabel = tk.Label(self, text="Game Over.", font=LARGE_FONT, background="blue")
answerlabel.pack()
self.ebutton.destroy()
def countdown(self, remaining = None):
if remaining is not None:
self.remaining = remaining
if self.remaining <= 0:
self.label.configure(text="Time's up!")
self.ebutton.destroy()
else:
self.label.configure(text="%d" % self.remaining)
self.remaining = self.remaining - 1
self.after(1000, self.countdown)
答案 0 :(得分:0)
调用after
会返回一个ID,您可以将其传递给after_cancel
以删除待处理的作业。因此,在开始新的计时之前,请跟踪此ID并杀死任何先前的计时器。
class Add(tk.Frame):
def __init__(self, parent, controller):
...
# initialize after_id to none
self.after_id = None
...
def time_start(self):
# kill the old timer
if self.after_id is not None:
self.after_cancel(self.after_id)
...
...
def countdown(self, remaining = None):
...
if self.remaining <= 0:
...
self.after_id = None
else:
...
self.after_id = self.after(1000, self.countdown)