【问题标题】:Tkinter is opening multiple GUI windows upon file selection with multiprocessing, when only one window should existTkinter 在使用多处理选择文件时打开多个 GUI 窗口,而应该只存在一个窗口
【发布时间】:2017-10-10 19:29:25
【问题描述】:

我有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 运行。

谢谢。

【问题讨论】:

  • 使用 root.withdraw() 消除 Tk() 窗口(发送到 GUI)。 askopenfilename() 打开它自己的窗口,这是您看到的第二个窗口effbot.org/tkinterbook/wm.htm 请注意,“dummy”将在 askopenfilename 返回后运行。

标签: python python-3.x tkinter multiprocessing python-multiprocessing


【解决方案1】:

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

这意味着将if __name__ == "__main__" 子句移动到程序的“底部”,并将与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()

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

【讨论】:

  • 感谢您的回复,但我无法打开包装。我有以下问题: 1. 什么是程序的“底部”?是在 root.mainloop() 之后吗? 2.当您提到移动if __name__ == "__main__"子句时,您指的是什么?整个代码块,还是整个函数?似乎至少 queue.put(path) 需要保持在原处。 3.当您提到将与tkinter相关的代码放在“那里”时,“那里”在哪里,什么是?是否在定义范围内?我不明白为什么会有tkinter 代码。
  • (续) 4. 当您提到在起点内定义的事件时,您是什么意思? 5. 最后,您多次引用tkinter 的代码...具体是什么意思?入口点是什么?
  • @user1318135 查看我的编辑。有关入口点的更多信息,请查看:docs.python.org/2/library/multiprocessing.html#windows
  • 这是否与在不运行整个导入文件的情况下无法在 Python 中使用 import 语句有关?我假设在 other_script.py 被调用之后,整个 primary.py 又开始了?
猜你喜欢
  • 1970-01-01
  • 2019-08-07
  • 1970-01-01
  • 2018-03-31
  • 2018-05-11
  • 1970-01-01
  • 2016-01-04
  • 2015-10-09
  • 2021-06-27
相关资源
最近更新 更多