首页 > 解决方案 > 出现文件选择对话框时,Tkinter GUI 消失

问题描述

背景:我正在为 PDF 应用程序构建 GUI。此应用程序要求用户选择文件的位置并提供一些附加信息,以便可以生成封面然后附加到 PDF。我选择了 Tkinter 来为这个应用程序创建 GUI。我在 Mac OS 上开发。

问题:我可以在按下表单的按钮时生成一个文件选择对话框,但是,在文件选择对话框出现后,GUI 立即消失。有人知道是什么原因造成的吗?

from tkinter import *
from tkinter import filedialog

root = Tk()
Label(root, text='Submittal No. ').grid(row=0)
Label(root, text='Project Name ').grid(row=1)
Label(root, text='Product Name ').grid(row=2)
e1 = Entry(root)
e2 = Entry(root)
e3 = Entry(root)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)

def fileSelector():
    root.withdraw()
    root.fileName = filedialog.askopenfilename()
    print(root.fileName)

Button(root, text='Select PDF file ', command=fileSelector).grid(row=3)

if __name__ == "__main__":
    mainloop()

标签: pythontkinter

解决方案


在您的 fileSelector 函数中,行 root.withdraw 用于使根窗口消失,同时使其保持活动状态。

您可以删除该行以使 GUI 保持可见,或者如果您想阻止用户与 GUI 交互,直到解决了 filedialog.askopenfilename,您可以稍后使用 deiconify 函数重新出现该窗口:

def fileSelector():
    global filename
    root.withdraw()
    root.fileName = filedialog.askopenfilename()
    root.deiconify()
    print(root.fileName)

推荐阅读