Lor*_*ger 1 python user-interface multithreading tkinter python-multithreading
我创建了一个 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()
Run Code Online (Sandbox Code Playgroud)
我想防止 GUI 在运行函数时冻结(在示例代码中它是确定按钮的功能)。为此,我找到了使用线程模块作为最佳实践的解决方案。但问题是,当我想再次运行代码时,python 返回此回溯:
RuntimeError: threads can only be started once
Run Code Online (Sandbox Code Playgroud)
我完全意识到错误消息中所述线程只能启动一次的问题。我的问题是:如何停止线程以再次启动它,或者是否有人有更好的解决方法来防止 GUI 冻结并多次按下按钮/运行函数?
BR,谢谢洛伦兹
您的代码将仅创建一个线程并将其start函数引用分配给command选项。因此,start()每当单击按钮时都会调用相同的函数。
您可以使用lambda:
command=lambda: threading.Thread(target=self.okbutton).start()
Run Code Online (Sandbox Code Playgroud)
然后,每当单击该按钮时,就会创建并启动一个新线程。