如何在 Python (tkinter) 中停止计时器?

编程入门 行业动态 更新时间:2024-10-25 15:25:56
本文介绍了如何在 Python (tkinter) 中停止计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我的目标是创建一个简单的计时器程序.它会不断更新自身,直到按下 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 07:13:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390584.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:计时器   如何在   Python   tkinter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!