【问题标题】:Tkinter Buttons and Multithreading?Tkinter 按钮和多线程?
【发布时间】:2020-09-24 06:01:16
【问题描述】:

关闭按钮在 python 中不起作用。我在 python 中有一个代码,我试图在函数 on 运行时让 off 按钮关闭函数。在运行时,它每 5 秒打印一次 hello,我希望关闭按钮停止此操作。每次我按下关闭按钮时,它都会在 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()

【问题讨论】:

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

标签: python multithreading tkinter


【解决方案1】:

您可以使用cancel()取消Timer()

timer_task = None

def on():
    global timer_task
    buttonstart.config(state=DISABLED)
    timer_task = threading.Timer(5.0, on)
    timer_task.start()
    print('hello')

def off():
    global timer_task
    if timer_task:
        timer_task.cancel()
        buttonstart.config(state=NORMAL)
        timer_task = None

【讨论】:

    猜你喜欢
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多