Tkinter线程错误:RuntimeError:线程只能启动一次

问题描述

我以以下结构创建了一个tkinter GUI:

import tkinter as tk
import threading

class App:
    def __init__(self,master):
        self.display_button_entry(master)

    def setup_window(self,master):
        self.f = tk.Frame(master,height=480,width=640,padx=10,pady=12)
        self.f.pack_propagate(0)

    def display_button_entry(self,master):
        self.setup_window(master)
        v = tk.StringVar()
        self.e = tk.Entry(self.f,textvariable=v)
        buttonA = tk.Button(self.f,text="Cancel",command=self.cancelbutton)
        buttonB = tk.Button(self.f,text="OK",command=threading.Thread(target=self.okbutton).start)
        self.e.pack()
        buttonA.pack()
        buttonB.pack()
        self.f.pack()

    def cancelbutton(self):
        print(self.e.get())
        self.f.destroy()

    def okbutton(self):
        print(self.e.get())


def main():
    root = tk.Tk()
    root.title('ButtonEntryCombo')
    root.resizable(width=tk.NO,height=tk.NO)
    app = App(root)
    root.mainloop()

main()

我想防止GUI在运行功能时冻结(在示例代码中,这是确定按钮的功能)。为此,我找到了使用线程模块作为最佳实践的解决方案。但是问题是,当我想再次运行代码时,python返回此回溯:

RuntimeError: threads can only be started once

我完全意识到线程只能按照错误消息中的说明启动一次的问题。我的问题是:如何停止第二次启动线程,或者有人有更好的解决方法来防止GUI冻结并多次按下按钮/运行某个函数

BR,谢谢 洛伦兹

解决方法

您的代码将仅创建一个线程并将其start函数引用分配给command选项。因此,每当单击按钮时,都会调用相同的start()函数。

您可以改用lambda

command=lambda: threading.Thread(target=self.okbutton).start()

然后,只要单击该按钮,就会创建并启动一个新线程。