如何为微波计时器增加额外的秒数



我对Python还处于初级水平,我自己也有一个简单的项目。我的目标是使用tkinter和python构建一个只有两个函数的简单计时器。第一个按钮在30秒时启动倒计时计时器。第二个按钮使它停止。然而,我希望每次额外按下第一个按钮,都能在倒计时钟上剩下的时间上再增加30秒。前两个元素已经证明使用这个先前的线程并不太困难,但向活动计时器添加额外的时间是我无法达到的。

本质上,目标是重新创建"+30秒";带有更新显示的微波炉上的按钮,第一次按下会增加30秒并启动计时器,每次按下会增加倒计时计时器30秒,第二次按下会停止计时器。

以下是我一直在使用的基本定时器逻辑。

def countdown(t=30):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="r")
time.sleep(1)
t -= 1
print('Done!')

由于以下原因,这个问题比看起来要复杂一点:

  1. 如果您没有使用任何库来处理并行事件,那么函数countdown((将阻塞主循环,并且在倒计时运行时您将无法执行任何操作(包括再次单击按钮以添加更多时间(

  2. 如果你想用同一个按钮添加时间,你必须检查屏幕上是否已经有倒计时打印,如果你没有检查,每次点击都会出现一个新的时钟。

我建议使用asyncio库如下:

import asyncio
# Create a global variable for the time
secs = 0 
#This function adds +30secs
def addTime():
global secs
secs+=30
#This is the func that gather the addTime function and the async clock
async def timerAction():
#This "while" is used to simulate multiple cliks on your button. 
# If you implement this as a callback delete the "while"
while True: 
j = 0 #Counter if a clock is already running
addTime() #Add time
for task in asyncio.all_tasks(): #This loop checks if there's a countdown already running
if task.get_name()=='countdown':
j+=1
if j == 0: #If no running countdown, j==0, and fires the countdown
taskCountdown = asyncio.create_task(countdown(), name='countdown')
await asyncio.sleep(10) #Wait 10secs between each call to the func (each call simulate a click)

async def countdown():
global secs
while secs>0:
mins, secs = divmod(secs, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="r")
await asyncio.sleep(1)
secs -= 1
print('Done!')
asyncio.run(timerAction())

输出:

第一次通话:

00:30

10秒后:

00:50

10秒后:

01:10

等等…

最新更新