python如何暂停计时器_如何在20分钟内停止计时器

我建议去掉while循环,而应该建立在turtle的ontimer()事件的基础上:from turtle import Turtle, Screen

from datetime import datetime

FONT = ("Arial", 50)

def start():

global timer_running, start_time

if timer_running:

return

start_time = datetime.now()

timer_running = True

screen.ontimer(lambda time=start_time: automatic_stop(time), 20 * 60 * 1000)

screen.ontimer(update, 100)

def update():

if not timer_running:

return

timerint = datetime.now() - start_time

marker.undo()

marker.write(timerint, align='center', font=FONT)

screen.ontimer(update, 100)

def manual_stop():

global timer_running

if not timer_running:

return

timer_running = False

timerint = datetime.now() - start_time

marker.undo()

marker.write(timerint, align='center', font=FONT)

def automatic_stop(time):

global timer_running

if timer_running and start_time == time: # make sure *this* timer is still valid

timer_running = False

marker.undo()

marker.write("Expired!", align='center', font=FONT)

screen = Screen()

marker = Turtle(visible=False)

marker.penup()

marker.write("Hit 'space' to start timer; 'p' to stop", align='center', font=FONT)

start_time = None

timer_running = False

screen.onkeypress(start, "space")

screen.onkeypress(manual_stop, "p")

screen.listen()

screen.mainloop()

我们传递automatic_stop()一个start_time的副本,这样当它在遥远的将来醒来时,它可以根据当前的start_time来检查它是否仍然是一个有效的结束事件。(如果您在Tk级别而不是turtle级别工作,则可以在不再需要计时器时取消计时器。)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值