Tkinter Threading Error: RuntimeError: threads can only be started once

Tkinter Threading Error: RuntimeError: threads can only be started once

我已经按照以下结构创建了一个 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 returns 这个回溯:

RuntimeError: threads can only be started once

我完全了解错误消息中所述线程只能启动一次的问题。我的问题是:我怎样才能停止线程以再次启动它,或者是否有人有更好的解决方法来防止 GUI 冻结并多次按下 button/running 一个函数?

BR,谢谢 洛伦兹

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

您可以使用 lambda 代替:

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

然后每当单击按钮时,都会创建并启动一个新线程。