当只应该存在一个窗口时,Tkinter 在使用多重处理选择文件时打开多个 GUI 窗口

2023-12-28

我有primary.py:

from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter import ttk
import multiprocessing as mp
import other_script

class GUI:
    def __init__(self, master):
        self.master = master

def file_select():

    path = askopenfilename()

    if __name__ == '__main__':
        queue = mp.Queue()
        queue.put(path)
        import_ds_proc = mp.Process(target=other_script.dummy, args=(queue,))
        import_ds_proc.daemon = True
        import_ds_proc.start()

# GUI
root = Tk()

my_gui = GUI(root)

# Display

frame = Frame(width=206, height=236)
frame.pack()

ttk.Button(frame, text="Select", command=file_select).pack(anchor='nw')

# Listener

root.mainloop()

和 other_script.py:

def dummy(parameter):
    pass

运行此程序时,选择文件后,会出现第二个 GUI 窗口。为什么?这是不受欢迎的行为,我反而想要dummy to run.

Thanks.


就像与multiprocessing,您需要放置代码来处理tkinter并使您的窗口位于程序的入口点内(这样它就不会通过另一个进程运行多次)。

这意味着移动if __name__ == "__main__"子句到程序的“底部”并将代码与tkinter而是在那里。您的入口点multiprocessing仍将受到保护,因为它是在事件之后调用的,该事件是在起始点内定义的。

Edit:入口点是你的程序输入的地方,通常当你说if __name__ == "__main__".

通过移动tkinter代码进入入口点,我的意思是这样的:

if __name__ == "__main__":
    root = Tk()
    my_gui = GUI(root)
    frame = Frame(width=206, height=236)
    frame.pack()
    ttk.Button(frame, text="Select", command=file_select).pack(anchor='nw')
    root.mainloop()

(在程序的“底部”,即定义所有函数之后。)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当只应该存在一个窗口时,Tkinter 在使用多重处理选择文件时打开多个 GUI 窗口 的相关文章

随机推荐