如何停止倒数计时彼此重叠?

时间:2019-01-10 15:51:52

标签: python tkinter

这是代码:

import tkinter as Alarm
class test(Alarm.Frame):
    def __init__(self, parent):
        Alarm.Frame.__init__(self, parent)
        self.prompt = Alarm.Label(self, text="Enter seconds:", anchor="w")
        self.entry = Alarm.Entry(self)
        self.output = Alarm.Label(self, text="Start")
        self.submit = Alarm.Button(self, text="Submit", command = self.startTimer)
        self.prompt.pack(side="top", fill="x")
        self.entry.pack(side="top", fill="x", padx=20)
        self.output.pack(side="top", fill="x", expand=True)
        self.submit.pack(side="right")
    def countdown(self, s):
        if s==0:
            self.output.configure(text="Alarm!")
            return  
        self.output.configure(text=str(s))
        s -= 1
        self.output.after(1000, lambda: self.countdown(s))
    def startTimer(self):
        try:
            i = int(self.entry.get())
            self.countdown(i)
        except ValueError:
            print("Please enter whole digits only in all boxes")
if __name__ == "__main__":
    root = Alarm.Tk()
    test(root).pack(fill="both", expand=True)
    root.mainloop()

因此对于此代码,它允许我创建一个倒数计时器。我想做的是,这样一来,如果倒计时已经在运行,那么如果设置了另一个倒计时,它将停止。

1 个答案:

答案 0 :(得分:1)

您可以使用一个很小的技巧来做到这一点。我有一个check变量,初始化为0。当您按下Submit按钮时,它将变为1。在倒数计时功能中,您可以检查其值并采取适当的措施。这是一个演示。

import tkinter as Alarm

class test(Alarm.Frame):
    def __init__(self, parent):
        Alarm.Frame.__init__(self, parent)
        self.prompt = Alarm.Label(self, text="Enter seconds:", anchor="w")
        self.entry = Alarm.Entry(self)
        self.output = Alarm.Label(self, text="Start")
        self.submit = Alarm.Button(self, text="Submit", command = self.startTimer)
        self.prompt.pack(side="top", fill="x")
        self.entry.pack(side="top", fill="x", padx=20)
        self.output.pack(side="top", fill="x", expand=True)
        self.submit.pack(side="right")
        self.check = 0
    def countdown(self, s):
        if self.check == 0:
            return
        if s==0:
            self.output.configure(text="Alarm!")
            return  
        self.output.configure(text=str(s))
        s -= 1
        self.output.after(1000, lambda: self.countdown(s))
    def startTimer(self):
        self.check = (self.check+1)%2
        try:
            i = int(self.entry.get())
            self.countdown(i)
        except ValueError:
            print("Please enter whole digits only in all boxes")
if __name__ == "__main__":
    root = Alarm.Tk()
    test(root).pack(fill="both", expand=True)
    root.mainloop()

Demo