如何在 Python (tkinter) 中停止计时器? [英] How do I stop a timer in Python (tkinter)?

查看:47
本文介绍了如何在 Python (tkinter) 中停止计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是创建一个简单的计时器程序.它会不断更新自身,直到按下 stopButton.但是,我不确定如何停止运行滴答功能,以便在按下 stopButton 后计时器保持不变.

My aim is to create a simple timer program. It updates itself constantly until the stopButton is pressed. However, I am unsure how to stop the tick function from running so that the timer stays the same once the stopButton is pressed.

这是我目前的代码:

import tkinter

root = tkinter.Tk()
root.title('Timer')
root.state('zoomed')

sec = 0

def tick():
    global sec

    sec += 0.1
    sec = round(sec,1)
    timeLabel.configure(text=sec)
    root.after(100, tick)

def stop(): 
    # stop the timer from updating.

timeLabel = tkinter.Label(root, fg='green',font=('Helvetica',150))
timeLabel.pack()

startButton = tkinter.Button(root, text='Start', command=tick)
startButton.pack()

stopButton = tkinter.Button(root, text='Stop', command=stop)
stopButton.pack()

root.mainloop()

停止 tick() 函数的可能方法是什么?

What would be a possible way of stopping the tick() function?

任何帮助将不胜感激!

推荐答案

您可以使用另一个全局变量来跟踪您当前是否应该计算滴答数.如果您不应该计算滴答数,只需让 tick 什么都不做(并且不要再次注册自己).

You can have another global that tracks whether you should currently be counting ticks. If you aren't supposed to be counting ticks, just have tick do nothing (and not register itself again).

import tkinter

root = tkinter.Tk()
root.title('Timer')
root.state('zoomed')

sec = 0
doTick = True

def tick():
    global sec
    if not doTick:
        return
    sec += 0.1
    sec = round(sec,1)
    timeLabel.configure(text=sec)
    root.after(100, tick)

def stop():
    global doTick
    doTick = False

def start():
    global doTick
    doTick = True
    # Perhaps reset `sec` too?
    tick()

timeLabel = tkinter.Label(root, fg='green',font=('Helvetica',150))
timeLabel.pack()

startButton = tkinter.Button(root, text='Start', command=start)
startButton.pack()

stopButton = tkinter.Button(root, text='Stop', command=stop)
stopButton.pack()

root.mainloop()

还可以进行其他结构改进(使用类来摆脱全局变量)和样式改进(snake_case 而不是 camelCase),但这应该让你指向正确的方向...

There are other structural improvements that could be made (using a class to get rid of the globals) and style improvements (snake_case instead of camelCase), but this should get you pointed in the right direction...

这篇关于如何在 Python (tkinter) 中停止计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆