python倒计时9到0_python为已经在运行的倒计时添加时间

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

啊!在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值