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

标签 python multithreading tkinter

但我正在尝试为我的脚本制作 GUI,当我单击 bt_send 时,我启动一个线程 (thread_enviar),该线程也会启动其他线程 (core),问题是 thread_enviar 永远运行,所以当我尝试再次单击 bt_send 时出现此错误:

File "/anaconda3/envs/tensor/lib/python3.6/threading.py", line 842, in start raise RuntimeError("threads can only be started once") RuntimeError: threads can only be started once

我的代码:

import tkinter as tk
from tkinter import filedialog
import pandas as pd
from tkinter import messagebox
from tkinter import ttk

import threading
import rnn10forecasting as rnn10f



filepath = ""
model = ""

'''def change_menu(selection):
    global model
    selected = selection
    print(selected)
    model = selected'''



def click():
    global filepath
    print("click")
    filepath = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("data files","*.csv"),("all files","*.*")))
    print(filepath)
    label_filepath.config(text = filepath)




def enviar():


    print(filepath)
    try:
        data = pd.read_csv(filepath)

    except:
        messagebox.showerror("Error", "Archivo .csv vacio o formato incompatible")


    if any(data.columns.values != ['date','close','volume','open','high','low']):
        messagebox.showerror("Error", "El archivo .csv no contiene la estructura requerida: [date,close,volume,open,high,low]")




    elif len(data) < 300:
        print("# registros")
        print(len(data))
        messagebox.showerror("Error", "El archivo de be contener como minimo 700 registros")



    else:

        pg_bar.start(500)
        core = threading.Thread(target=rnn10f.forecasting, args=(filepath,))
        #core.daemon = True
        core.start()
        core.join()
        print("VIVO?")
        print(core.isAlive())
        pg_bar.stop()



    return print(thread_enviar.is_alive())



thread_enviar = threading.Thread(target=enviar, args=())


window = tk.Tk()

window.resizable(width=False, height=False)

window.title("LSTM Module")

window.geometry("600x150")


title = tk.Label(text="StockForecaster", font=("Times New Roman", 30))
title.place(relx=0.1, rely=0.05, relwidth=0.8, relheight=0.25)


bt_select = tk.Button(text="Select File", bg="blue", command= click)
bt_select.place(relx=0.7, rely=0.4, relwidth=0.25, relheight=0.2)


label_filepath = tk.Label(text="Please select a .csv File")
label_filepath.place(relx=0, rely=0.4, relwidth=0.7, relheight=0.15)


options = tk.StringVar()



bt_send = tk.Button(text="Send", bg="blue", command=thread_enviar.start)
bt_send.place(relx=0.70, rely=0.7, relwidth=0.25, relheight=0.20)


pg_bar = ttk.Progressbar(window, orient= tk.HORIZONTAL, mode="indeterminate", )
pg_bar.place(relx=0.10, rely=0.75, relwidth=0.55, relheight=0.05)


window.mainloop()

我不知道是否有任何方法可以杀死该线程,或者我是否做错了什么。

最佳答案

Question: RuntimeError: threads can only be started once

据我了解,您不想运行多个线程,您只想在线程中执行任务以避免卡住Tk( ).mainloop().
要禁止,要在先前的线程仍在运行时启动新的线程,您必须禁用按钮或验证之前的线程是否仍然是.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()

关于python - tkinter:运行时错误:线程只能启动一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54395358/

相关文章:

c++ - boost 线程互斥数组

c++ - 使用接受 char 指针的函数调用 pthread_create

python - 我可以在自定义 Tkinter Toplevel() 窗口上获取消息框的图标 ="warning"噪音吗?

Python Mock Patch 一个类中的多个方法

python - 将python中的numpy.ndarray保存为图像

python - .Pytest session 范围固定装置显示 pylint 中的错误

java - 在 Java 中避免超时/饥饿的常见做法?

Python - 在类中初始化 tkinter,当在另一个类中需要另一个 gui 时会发生什么?

python - Tkinter 侧边栏

python - 在 Python (PIL) 中读取带有损坏 header 的 JPEG