Tom Crews
Tom Crews

Reputation: 135

Tkinter GUI disappears when file selection dialog appears

Background: I am building a GUI for a PDF app. This app requires that the user select the location of the file and provide some additional information so that a cover page can be generated and then appended to a PDF. I have chosen Tkinter to create the GUI for this app. I developing on Mac OS.

Problem: I am able to generate a file selection dialog upon pressing the form's button, however, the GUI disappears immediately after the file selection dialog appears. Does someone know what is causing this?

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

Upvotes: 0

Views: 584

Answers (2)

Gonzalez87
Gonzalez87

Reputation: 172

In your fileSelector function, the line root.withdraw is used to make the root window disappear while keeping it alive.

You can either remove that line so the GUI stays visible or if you want to prevent the user from interacting with the GUI until the filedialog.askopenfilename is resolved, you can make the window reappear later with the deiconify function :

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

Upvotes: 2

ViG
ViG

Reputation: 1868

The reason your GUI disappears is because of the statement

 root.withdraw()

Delete this statement and your GUI remains visible.

Upvotes: 2

Related Questions