如何使用多重处理启动一个单独的新Tk()窗口? [英] How to start a separate new Tk() window using multiprocessing?
问题描述
以下代码是可运行的,您只需复制/粘贴即可:
The following code is runnable, you can just copy/paste:
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()
窗口.当我单击创建按钮时,我只得到原始窗口(而不是预期的窗口),它给了我这个错误:
So I simply want to create a completely separated Tk()
window using multiprocessing. When I click on the create button, I just get the original window (not the intended one) and it gives me this error:
AttributeError: Can't pickle local object 'createClientsWin.<locals>.startProcess'
*有人可以解释如何使用多处理程序启动一个单独的新Tk()窗口吗? *
更新:不是重复
即使我遵循可能重复的问题中提供的解决方案,也无助于解决我的问题.仅仅是因为,在我的案例中使用了Tkinter.修改后的代码:
Even if I follow the solution provided in the possible duplicate question, that doesn't help solving my question. Simply because, Tkinter is being used in my case. The modified code:
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()
应该移至全局范围.
Function in global scope should be used for multiprocess target function, so the startProcess()
should be moved into global scope.
此外,对startProcess()
中的if __name__ == "__main__"
进行检查也会导致if块中的代码无法执行.
Also the checking of if __name__ == "__main__"
inside startProcess()
will cause the code inside the if block not being executed.
最后,创建startingWin
的位置应放在if __name__ == "__main__"
块中,否则启动的每个进程都将创建startingWin
.
Finally the creation of startingWin
should be put inside if __name__ == "__main__"
block, otherwise every process started will create the startingWin
.
以下是解决上述问题的建议更改:
Below is the proposed changes to solve the above issues:
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()
这篇关于如何使用多重处理启动一个单独的新Tk()窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!