Python Tkinter按钮和多线程?

Python Tkinter按钮和多线程?,python,multithreading,tkinter,Python,Multithreading,Tkinter,关闭按钮在python中不起作用。我有一段python代码,其中我试图在函数运行时使用off按钮关闭函数。当on运行时,它每5秒打印一次hello,我希望关闭按钮停止此操作。每次我按下off按钮,它都会在hello仍在播放或python崩溃时冻结。我怎样才能解决这个问题 以下是我目前掌握的代码: from tkinter import * import threading root = Tk() def on(): threading.Timer(5.0, on).start()

关闭按钮在python中不起作用。我有一段python代码,其中我试图在函数运行时使用off按钮关闭函数。当on运行时,它每5秒打印一次hello,我希望关闭按钮停止此操作。每次我按下off按钮,它都会在hello仍在播放或python崩溃时冻结。我怎样才能解决这个问题

以下是我目前掌握的代码:

from tkinter import *
import threading

root = Tk()

def on():
    threading.Timer(5.0, on).start()
    print("hello")

def off():
    exit()
    
buttonstart = Button(root, text="on", command=on)
button = Button(root, text="off", command=off)
buttonstart.pack()
button.pack()
root.mainloop()

您可以使用
cancel()
取消
计时器()

timer\u task=None
def on():
全局计时器任务
buttonstart.config(状态=已禁用)
timer_task=threading.timer(5.0,开)
计时器_任务。开始()
打印('你好')
def off():
全局计时器任务
如果计时器执行任务:
计时器任务。取消()
buttonstart.config(状态=正常)
计时器任务=无

不清楚为什么您的问题中有这么多重复的代码-这是故意的吗?如果没有,请回答您的问题并解决它。也就是说,一般来说,
tkinter
不支持多线程。此代码不使用线程,它启动计时器,而
off
尝试退出应用程序,而不是停止计时器。