且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

tkinter:运行时错误:线程只能启动一次

更新时间:2023-11-18 13:14:22

问题:RuntimeError:线程只能启动一次

Question: RuntimeError: threads can only be started once

据我所知,您不想运行多个 threads,您只想在 thread 中执行 Task 以避免冻结 Tk().mainloop().
要在前一个 thread 仍在运行时启动一个新的 thread,您必须disable Button 或验证之前的 thread 是否仍然是 .alive().

As I understand, you don't want to run multiple threads, you only want to do a Task in a thread to avoid freezing the Tk().mainloop().
To inhibit, to start a new thread while the previous thread are still running you have to disable the Button or verify if the previous thread is still .alive().

import tkinter as tk
import threading, time

class Task(threading.Thread):
    def __init__(self, master, task):
        threading.Thread.__init__(self, target=task, args=(master,))

        if not hasattr(master, 'thread_enviar') or not master.thread_enviar.is_alive():
            master.thread_enviar = self
            self.start()

def enviar(master):
    # Simulating conditions
    if 0:
        pass
    #if any(...
    #elif len(data) < 300:
    else:
        #master.pg_bar.start(500)

        # Simulate long run
        time.sleep(10)
        #rnn10f.forecasting(filepath)

        print("VIVO?")
        #master.pg_bar.stop()

class App(tk.Tk):
    def __init__(self):
        super().__init__()

        bt_send = tk.Button(text="Send", bg="blue", 
                            command=lambda :Task(self, enviar))

if __name__ == "__main__":
    App().mainloop()