我正在尝试做一个pomodoro计时器,它将显示不同的倒计时点击三个按钮选项之一。在
这里的问题是,每次我在之前单击一个按钮之后单击一个按钮,标签都会为显示哪个计时器而烦恼。它试图同时显示两个定时器倒计时。在
当我点击另一个按钮时,我需要标签停止显示第一个按钮的定时器倒计时。我的代码是:
from tkinter import *
class Application(Frame):
def __init__(self,master):
super(Application,self).__init__(master)
self.pack()
self.createWidgets()
def createWidgets(self):
self.labelvariable = StringVar()
self.labelvariable.set("25:00")
self.thelabel = Label(self,textvariable = self.labelvariable,font=('Helvetica',50))
self.thelabel.pack(side=TOP)
self.firstButton = Button(self,text="pomodoro",command=self.pomodoro)
self.firstButton.pack(side=LEFT)
self.secondButton = Button(self,text="short break",command=self.shortBreak)
self.secondButton.pack(side=LEFT)
self.thirdButton = Button(self,text="long break",command=self.longBreak)
self.thirdButton.pack(side=LEFT)
def pomodoro(self):
countdown(1500)
def shortBreak(self):
countdown(300)
def longBreak(self):
countdown(600)
def countdown(timeInSeconds):
mins,secs = divmod(timeInSeconds,60)
timeformat = "{0:02d}:{1:02d}".format(mins,secs)
app.labelvariable.set(timeformat)
root.after(1000,countdown,timeInSeconds-1)
if __name__ == '__main__':
root = Tk()
root.title("Timer")
app = Application(root)
root.mainloop()
这里有一个可能的解决方案。这个函数将
countdown
函数移到Application
类中,并使其自由运行。然后我添加了一个class属性来跟踪当前剩余时间,并将其递减为0。这确实有一个缺点,即可能需要几乎一秒钟的时间来显示新的计数。在这是另一个基于Curly Joe的comment的选项。它使用
^{pr2}$after_cancel
来取消下一个报警,从而停止当前正在运行的倒计时。它的好处是新的倒计时立即开始。在相关问题 更多 >
编程相关推荐