首页 > 解决方案 > 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()

标签: python-3.xtkintermultiprocessingfunction-call

解决方案


这是一个可以帮助您入门的独立示例:

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()

推荐阅读