如何在python tkinter中停止此功能

时间:2019-09-06 05:59:20

标签: python tkinter

我正在尝试制作一个Stopwatch程序,每当我按下按钮运行它时,函数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()

2 个答案:

答案 0 :(得分:1)

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

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()

答案 1 :(得分:0)

您可以添加全局变量,例如“退出”,

并在l1.after(1000,watch)之前添加if语句

C++

在stop()中,您可以编写

.h