【问题标题】:Tkinter Threading Error: RuntimeError: threads can only be started onceTkinter 线程错误:RuntimeError:线程只能启动一次
【发布时间】:2020-12-13 03:59:35
【问题描述】:

我创建了一个 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,谢谢 洛伦兹

【问题讨论】:

    标签: python multithreading user-interface tkinter python-multithreading


    【解决方案1】:

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

    您可以改用lambda

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

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

    【讨论】:

    • 您在另一个线程中为类似问题分享了另一个可行的解决方案:stackoverflow.com/questions/63450516/… 您的两个解决方案都对我有用,我想知道两者之间的相关区别是什么,哪个会成为“最佳实践”?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-09
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多