我想说代码的设计中有一个缺陷,因为你的屏幕输出阻止了整个程序什么都不做(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”)以及它使软件更难调试/维护。在
啊!在