【问题标题】:How to add additional seconds to a microwave timer?如何为微波炉定时器增加额外的秒数?
【发布时间】:2022-01-15 19:47:36
【问题描述】:

我在 Python 方面处于非常初级的水平,我自己有一个简单的项目。我的目标是使用 tkinter 和 python 构建一个只有两个函数的简单计时器。第一个按钮在 30 秒时启动倒数计时器。第二个按钮停止它。但是,我希望每多按一下第一个按钮,就可以在倒计时时钟上当前剩余的任何时间增加 30 秒。使用prior thread 证明前两个元素并不太难,但我无法为活动计时器增加额外的时间。

基本上,我们的目标是重新创建微波炉上“+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!')

【问题讨论】:

  • 你在使用异步库吗? (如 asycio 或线程)
  • 究竟是什么影响范围太大了?请edit您的问题并展示您的尝试。
  • 离题:time.sleep() 很大程度上与tkinter 不兼容。一个常见的解决方法是使用通用的after() 小部件方法定期更新到计时器。
  • 我认为你需要定义一个class Timer来封装one的状态和改变它的方法(例如start()stop()pause()add_30_secs())。

标签: python time countdown


【解决方案1】:

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

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

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

我建议使用asyncio lib 如下:

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

等等……

【讨论】:

    猜你喜欢
    • 2022-06-12
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多