[英]tkinter button command: 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 返回此回溯:
RuntimeError: threads can only be started once
我完全意识到线程只能启动一次的问题,如错误消息中所述。 我的问题是:如何停止线程以再次启动它,或者是否有人有更好的解决方法来防止 GUI 冻结并多次按下按钮/运行某个功能?
BR,谢谢洛伦兹
您的代码只会创建一个线程并将其start
函数引用分配给command
选项。 因此,无论何时单击按钮,都会调用相同的start()
函数。
您可以改用lambda
:
command=lambda: threading.Thread(target=self.okbutton).start()
然后每当单击按钮时,将创建并启动一个新线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.