如何使用多处理来启动单独的新TK()窗口



以下代码可运行,您可以复制/粘贴:

from tkinter import *
import multiprocessing
startingWin = Tk()
def createClientsWin():
    def startProcess():
        clientsWin = Tk()
        label = Label(clientsWin, text="Nothing to show")
        label.grid()
        clientsWin.mainloop()
    if __name__ == "__main__":
        p = multiprocessing.Process(target=startProcess)
        p.start()
button = Button(startingWin, text="create clients", command=lambda: createClientsWin())
button.grid()
startingWin.mainloop()

因此,我只想使用多处理创建一个完全分开的Tk()窗口。当我单击创建按钮时,我只获取原始窗口(不是打算的窗口),它给了我这个错误:

AttributeError: Can't pickle local object 'createClientsWin.<locals>.startProcess'

*有人可以解释如何使用多处理启动单独的新TK()窗口?*

更新:不是重复

即使我遵循可能的重复问题中提供的解决方案,这也无助于解决我的问题。仅仅是因为在我的情况下,正在使用TKINTER。修改的代码:

def createClientsWin():
    clientsWin = Tk()
    label = Label(clientsWin, text="Nothing to show")
    label.grid()
    clientsWin.mainloop()
def createClientsWinProcess():
    if __name__ == "__main__":
        p = multiprocessing.Process(target=createClientsWin)
        p.start()
startingWin = Tk()
button = Button(startingWin, text="create clients", command=lambda: createClientsWinProcess())
button.grid()
startingWin.mainloop()

全局范围中的函数应用于多进程目标函数,因此startProcess()应移至全局范围。

此外,在startProcess()内的if __name__ == "__main__"检查也会导致IF Block内部的代码。

最后,应将startingWin的创建放置在if __name__ == "__main__"块中,否则每个启动过程都会创建startingWin

以下是解决上述问题的建议更改:

from tkinter import *
import multiprocessing
def startProcess():
    clientsWin = Tk()
    label = Label(clientsWin, text="Nothing to show")
    label.grid()
    clientsWin.mainloop()
def createClientsWin():
    p = multiprocessing.Process(target=startProcess)
    p.start()
if __name__ == '__main__':
    startingWin = Tk()
    button = Button(startingWin, text="create clients", command=createClientsWin)
    button.grid()
    startingWin.mainloop()

在与TKINTER一起使用多处理时,使用类更容易。尝试以下代码:

import tkinter as Tk
import multiprocessing as mp
class A:
    def __init__(self, master):
        self.master = master
        label = Tk.Label(self.master, text = 'A')
        label.pack()
        root_b = Tk.Toplevel()
        GUI_B = B(root_b)
        mp.Process(target = GUI_B.mainloop())
    def mainloop(self):
        self.master.mainloop()
class B:
    def __init__(self, master):
        self.master = master
        label = Tk.Label(self.master, text = 'B')
        label.pack()
    def mainloop(self):
        self.master.mainloop()
if __name__=='__main__':
    root = Tk.Tk()
    GUI_A = A(root) 
    mp.Process(target = GUI_A.mainloop())

相关内容

  • 没有找到相关文章

最新更新