python-3.x - Tkinter 中的多处理
问题描述
我有以下代码,我从按钮调用函数,该按钮从小部件获取输入。这是一个需要大约 4 分钟才能运行的函数,为了解决 tkinter 窗口的“无响应”问题,我想让 func 进程在不同的核心上运行并终止,因为它可以通过在 mainloop 上运行的应用程序再次调用一个不同的论点。我阅读了 multiprocessing 的文档,并且 Pool 似乎是这里的选择,但我不知道如何在这里构建它。尝试了一些错误的东西。
class database(tk.Tk):
def __init__(self, *args, *kwargs):
tk.Tk.__init__(self, *args, **kwargs):
container= tk.Frame(self, width=1000, height=1000)
container.pack(side="top", fill="both", expand= True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in ( msPage): #many more pages here
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(msPage)
def show_frame(self,cont):
frame = self,frames[cont]
frame.tkraise()
def MarkS(msVar):
ms.func(msVar.get()) # func takes about 4 mins
class msPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
msVar = StringVar()
msCal = Calendar(self, selectmode='day'
textvariable=msVar).pack(fill="both", expand=True)
# button2 calls MarkS
button2 = ttk.Button(self,
text="Get Data",
command=lambda: MarkS(msVar)).pack(pady=30, padx=10)
app = database()
app.geometry("1066x568")
app.minsize(width=670, height=550)
app.mainloop()
解决方案
这是一个可以帮助您入门的独立示例:
from multiprocessing import Process
class ms_var_class():
value = None
def __init__(self, value):
self.value = value
def get(self):
return self.value
# This is to simulate type(ms)
class ms_class():
process = None
# This is for simulating your long running function
def func(self, ms_var):
print(ms_var)
def MarkS(msVar):
ms.process = Process(target=ms.func, args=(msVar.get(),))
ms.process.start()
# Call ms.process.join() later
ms_var = ms_var_class("bogus")
ms = ms_class()
MarkS(ms_var)
if ms.process is not None:
ms.process.join()
推荐阅读
- php - 从私钥生成 CSR 密钥
- angular - 在 Angular 中动态加载组件
- javascript - 在框内水平移动垂直线
- postgresql - Postgresql 命令行实用程序无法在 WSL 上启动
- node.js - GraphQL 动态模式
- security - 防止 curl(或 wget)从目标 URL 中删除“../”?
- javascript - TypeScript:强制在键上命名和在值上键入,这可能吗?
- laravel - Laravel 验证错误不仅适用于图像
- angular - 如何为预填充的输入字段添加错误消息
- javascript - 点击后如何使文本在图像上出现和消失。