I cannot launch a TopLevel window after FileDialog execution

I cannot launch a TopLevel window after FileDialog execution
python
Ethan Jackson

Why can I not show a TopLevel window after launching the FileDialog module?

I would like to show a window with a waiting message after executing FileDialog code.


  • If I create the TopLevel window before calling FileDialog, the window is displayed and then the FileDialog code is executed.

  • But if I run FileDialog first, then create the TopLevel, this window is not displayed.

This code works fine:

import time from tkinter import filedialog from tkinter import * root = Tk() root.title("Main window") root.geometry("400x200") topLevelWindow = Toplevel(root) topLevelWindow.title("Secondary window") topLevelWindow.geometry("400x200") Label(topLevelWindow, text="Plaese wait...").pack() # Choose a file and save the path filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = [("All files", "*.*")]) print("File path: ", filename)

But if I execute TopLevel code after FileDialog, it does not show the TopLevel window:

import time from tkinter import filedialog from tkinter import * root = Tk() root.title("Main window") root.geometry("400x200") # Choose a file and save the path filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = [("All files", "*.*")]) topLevelWindow = Toplevel(root) topLevelWindow.title("Secondary window") topLevelWindow.geometry("400x200") Label(topLevelWindow, text="Plaese wait...").pack() print("File path: ", filename)

Thanks in advance for any help!

I wish to launch TopLevel windows after the FileDialog execution.

Answer

The filedialog.askopenfilename() blocks the main thread with its own event loop; After it closes, the Toplevel is created but not rendered immediately.

To reliably launch a Toplevel window after a filedialog.askopenfilename() call, you must ensure that Tk() window and mainloop() are running, and call the fileDialog inside an event callback.

Something like this should work:

from tkinter import filedialog, Toplevel, Label, Button, Tk def open_file_and_show_window(): filename = filedialog.askopenfilename( title="Select a file", filetypes=[("All files", "*.*")] ) print("Selected file:", filename) top = Toplevel(root) top.title("Processing Window") top.geometry("300x100") Label(top, text="Please wait...").pack(pady=20) root = Tk() root.title("Main Window") root.geometry("400x200") Button(root, text="Choose File", command=open_file_and_show_window).pack(pady=50) root.mainloop()

Related Articles