在运行的倒计时中添加时间
我想做一个应用程序,点击一个按钮就能给我正在倒计时的计时器增加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)
这个函数时,它都会开始倒计时15秒,而如果我点击按钮,什么也不会发生,直到这个计时器结束。
如果能帮忙就太好了。
2 个回答
0
我可能会有一个叫做 Timer
的对象,这个对象里面有一个叫 finish
的属性,我可以简单地给它加一个整数。然后让这个 timer
在另一个线程里运行,这样你就可以从你的图形界面(GUI)中查询到当前剩余的时间。
class Timer(object):
def __init__(self, length):
self.finish = time.time() + length
def get_time(self):
return time.time() >= self.finish
1
我觉得这个代码设计上有个问题,因为你的屏幕输出让整个程序停在那里什么都不做(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中你要尽量避免使用线程,因为它往往(但并不总是)会让程序变慢(可以参考“全局解释器锁”),而且会让软件更难调试和维护。
希望这对你有帮助!