Tkinter 在使用多处理选择文件时打开多个 GUI windows,而只有一个 window 应该存在

Tkinter is opening multiple GUI windows upon file selection with multiprocessing, when only one window should exist

我有 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 window。为什么?这是不希望的行为,我希望 dummy 到 运行。

谢谢。

就像 multiprocessing 一样,您需要将与 tkinter 相关的代码放在程序的入口点内并使 window 成为程序的入口点(这样它就不是 运行 不止一次通过另一个进程)。

这意味着将 if __name__ == "__main__" 子句移动到程序的 'bottom' 并将与 tkinter 相关的代码放在那里。 multiprocessing 的入口点仍将受到保护,因为它是在起点内定义的事件之后调用的。

编辑: 入口点是你的程序从哪里进入,通常当你说 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()

(在程序的 'bottom' 处,即在定义所有函数之后。)