python - 如何在 python tkinter 中停止此函数

标签 python tkinter

我正在尝试制作一个秒表程序,每当我按下按钮运行它时,函数 def watch() 就会不断执行,并且在需要时我无法停止它。

有什么方法可以在按下按钮后停止 def watch() 函数的执行吗?

谢谢你...

from tkinter import *

root = Tk()

tog = 0

hour = 0
mins = 0
sec = 0


def toggle():
    global tog
    tog = tog + 1

    if tog == 1:
        watch()
    elif tog == 2:
        stop()
        tog = 0

def stop():
    donothing = 0

def watch():
    global sec
    global hour
    global mins

    sec = sec + 1
    l1.config(text=sec)
    l1.after(1000,watch)



    l1 = Label(root)
    l1.pack()

Button(root,text="Start",command= lambda: toggle()).pack()

root.mainloop()

最佳答案

您应该保留对 after 调用的引用,并在 toggleFalse 时取消回调。您可以通过使用 tkinter 变量来避免丑陋的 global 声明,这些变量是可以读取或设置值的对象。

import tkinter as tk


def toggle_on_off():
    toggle.set(not toggle.get())
    if toggle.get():
        watch()

def watch():
    count_seconds.set(count_seconds.get() + 1)
    if toggle.get():
        _callback_id.set(root.after(1000, watch))
    else:
        root.after_cancel(_callback_id.get())
        
root = tk.Tk()

count_seconds = tk.IntVar(root)
count_seconds.set(0)
toggle = tk.BooleanVar(root)
toggle.set(False)

Button(root,text="Start",command=toggle_on_off).pack()
label = tk.Label(root, textvariable=count_seconds)
label.pack()

_callback_id = tk.StringVar(root)
_callback_id.set(None)

root.mainloop()

[编辑]

与全局变量相同的代码是这样的:

import tkinter as tk


def toggle_on_off():
    global toggle
    toggle = not toggle
    if toggle:
        watch()

def watch():
    global count_seconds, _callback_id
    count_seconds += 1
    label.configure(text=str(count_seconds))
    if toggle:
        _callback_id = root.after(1000, watch)
    else:
        root.after_cancel(_callback_id)
        
root = tk.Tk()

count_seconds = 0
toggle = False

Button(root,text="Start",command=toggle_on_off).pack()
label = tk.Label(root, text=str(count_seconds))
label.pack()

_callback_id = None

root.mainloop()

关于python - 如何在 python tkinter 中停止此函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57816486/

相关文章:

python - 无法更改应用引擎应用程序中的前端实例类

python - python中分类变量的knn插补

python - 在哪里可以找到在 Python shell 中加载的第一个文本并对其进行更改?

python - 更改 Tkinter 列表框中项目的颜色

python - Django 模板不存在?

python - 使用 SQLAlchemy 和 MySQL 进行浮点值舍入

python - 如何处理 Tkinter 中的窗口关闭事件?

python - 如何在 Python 中使用循环创建单选按钮

python - 基于 tkinter 的程序中彩色滚动条的其他选项?

python - 复选按钮返回值