Skip to main content
 首页 » 编程设计

python将时间添加到已经运行的倒计时

2025年05月04日8kenshinobiy

我想要一个应用程序,如果我点击一个按钮,我的倒数计时器会增加 X 的时间。

我猜我必须为此使用线程,但我不确定如何实现它。

这是我目前的代码:

def countdown_controller(add_time): 
    end_it = False 
    def timer(time_this): 
        start = time.time() 
        lastprinted = 0 
        finish = start + time_this 
        while time.time() < finish: 
            now = int(time.time()) 
            if now != lastprinted: 
                time_left = int(finish - now) 
                print time_left 
                lastprinted = now 
            if end_it == True: 
                now = finish 
            time.sleep(0.1) 
    # Check if the counter is running otherwise just add time. 
    try: 
        time_left  
    except NameError: 
        timer(add_time) 
    else: 
        if time_left == 0: 
        timer(add_time) 
        else: 
            add_this = time_left 
            end_it = True 
            while now != finish: 
                time.sleep(0.1) 
            timer(add_time + add_this) 

显然这是行不通的,因为每次我调用 countdown_controller(15) fx 时,它都会开始倒计时 15 秒,如果我点击我的按钮,在计时器结束之前什么都不会发生。

帮助将不胜感激。

请您参考如下方法:

我会说代码的设计存在缺陷,因为您的屏幕输出阻止了整个程序的无所事事 (time.sleep(0.1))。

在这些情况下,通常您想要做的是在您的程序中有一个主循环,循环执行使您的程序运行的各种操作。这保证了系统资源在各种任务之间的合理分配。

在您的特定情况下,您希望在主循环中拥有的是:

  • 检查用户输入(是否添加了额外时间?)
  • 更新倒计时输出

示例实现:

import time 
import curses 
 
# The timer class     
class Timer(): 
    def __init__(self): 
        self.target = time.time() + 5 
    def add_five(self): 
        self.target += 5 
    def get_left(self): 
        return int(self.target-time.time()) 
 
# The main program 
t = Timer() 
stdscr = curses.initscr() 
stdscr.nodelay(True) 
curses.noecho() 
# This is the main loop done in curses, but you can implement it with 
# a GUI toolkit or any other method you wish. 
while True: 
    left = t.get_left() 
    if left <= 0: 
        break 
    stdscr.addstr(0, 0, 'Seconds left: %s ' % str(left).zfill(3)) 
    c = stdscr.getch() 
    if c == ord('x') : 
        t.add_five() 
# Final operations start here 
stdscr.keypad(0) 
curses.echo() 
curses.endwin() 
print '\nTime is up!\n' 

如果您按下 x 键(小写),上述程序将增加 5 秒的计数器。大多数代码是使用 curses 模块的样板,但当然,如果您使用 PyGTK、PySide 或任何其他图形工具包,它就会有所不同。

编辑: 根据经验,在 Python 中您希望尽可能避免线程化,因为它经常(但不总是)减慢程序速度(参见“Global Interpreter Lock” ) 并且因为它使软件更难调试/维护。

喂!