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

回眸只為那壹抹淺笑 提交于 2021-02-10 08:08:27

问题


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

And other_script.py:

def dummy(parameter):
    pass

When running this, upon selection of a file, a second GUI window appears. Why? This is undesired behavior, I instead want dummy to run.

Thanks.


回答1:


Just like with multiprocessing, you need to place the code to do with tkinter and making your window within the entry point to your program (such that it is not ran more than once through another process).

This means moving the if __name__ == "__main__" clause to the 'bottom' of your program and placing the code to do with tkinter in there instead. The entry point to your multiprocessing will still be protected as it is called after an event, which is defined within the start point.

Edit: The entry point is where your program is entered from, normally when you say if __name__ == "__main__".

By moving the tkinter code into the entry point, I mean something like this:

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

(At the 'bottom' of your program, i.e. after all functions are defined.)



来源:https://stackoverflow.com/questions/46674498/tkinter-is-opening-multiple-gui-windows-upon-file-selection-with-multiprocessing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!