如何在20分钟停止计时器

时间:2017-06-22 22:06:14

标签: python python-3.x datetime timer

我正在制作一个计时器,当用户点击“空格”时停止并停在“p”上,显示结束时间。我可以在20分钟的最长时间停止吗?有什么像

if time_passed==20:
    break

我的代码:

from turtle import*
from datetime import datetime

...

def start():
    undo()
    global break1, timerint, startime
    break1 = 0
    startime = datetime.now()
    while True:
        timerint = datetime.now()-startime
        write(timerint,font=("Arial",50))
        undo()
        if break1 == 1:
            break


def stop():
    global break1, timerint, startime
    timerint=datetime.now()-startime
    write(timerint,font=("Arial",50))
    break1 = 1


# Turtle placement code removed
onkeypress(start,"space")
onkeypress(stop,"p")
listen()

2 个答案:

答案 0 :(得分:2)

不,但您始终可以使用time.time()方法检查已用时间。

import time
start = time.time()

while ...
    ....
    now = time.time()
    if now - start > 20 * 60:
        break

这是低科技版本。如果您想要更复杂的东西,例如单独的计时器进程,请尝试完整的浏览器搜索“Python计时器进程”。

另外,您可以考虑使用布尔值:

global timer_running, timerint, startime
timer_running = True
startime = datetime.now()
while timer_running:
    timerint = datetime.now()-startime
    write(timerint,font=("Arial",50))
    undo()

def stop():
    global timer_running, timerint, startime
    timerint = datetime.now()-startime
    write(timerint, font=("Arial", 50))
    timer_running = False

答案 1 :(得分:0)

我建议摆脱while循环,而是建立在海龟的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级而不是乌龟级别工作,则可以在不再需要时取消计时器。)