【发布时间】: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