0

The following code display a window without the default title bar. This window contains a button that asks the user to select a file. Unfortunatly, when the button is clicked the popup asking the user to select a file appears behind the main window. How can I ensure that the popup appears on top of the window?

Note: if the line window.overrideredirect(True) is commented, the popup appears on top of the window, but the default title bar is back.

import tkinter as tk
from tkinter import filedialog as fd


def open_file():
    model_file = fd.askopenfile(title="Select model", filetypes=(
        ('model files', '*.pt'),
        ('All files', '*.*')
    ))
    print(model_file)


if __name__ == '__main__':
    window = tk.Tk()
    window.geometry("+100+100")
    window.overrideredirect(True) # When commented the code works properly.

    button = tk.Button(
        window, text='Select a file', command=open_file
    )
    button.grid(row=0, column=0)

    # Provide a way to easily exit.
    button2 = tk.Button(
        window, text='Exit', command=window.quit
    )
    button2.grid(row=1, column=0)

    window.mainloop()

martineau
  • 119,623
  • 25
  • 170
  • 301
Theophile Champion
  • 453
  • 1
  • 4
  • 20
  • FWIW, the `askopenfile` popup is **not** behind the main window on my Windows system (and it has the focus). – martineau Apr 06 '22 at 16:33
  • Oh, does it means that it is a linux related issue? (I am on Ubuntu) – Theophile Champion Apr 06 '22 at 16:38
  • 1
    Perhaps call `.withdraw()` and `.deiconify()` on your main window around the call to the file dialog? – jasonharper Apr 06 '22 at 16:46
  • Could be an OS issue, because how `overrideredirect` works internally would be very OS-dependent. It could also have something to do with how `askopenfile` is implemented — because I would expect focus being shifted to its dialog the normal behaviour. – martineau Apr 06 '22 at 16:46
  • Thanks @jasonharper, your solution works. However, this is not optimal in terms of user experience. – Theophile Champion Apr 06 '22 at 17:00
  • @martineau it seems to be an OS related issue. I have tried to create a second window in the open_file function, i.e. `window2 = tk.Tk()`. Then, no function seems to be able to pull this second window on top of the first one. I tried `window2.lift()`, `window2.focus_force()` and `window2.attributes("-topmost", True)`. – Theophile Champion Apr 06 '22 at 17:07
  • 1
    @Theophile: Can't say I'm surprised creating another instance of `Tk` didn't work — it usually doesn't (see [Why are multiple instances of Tk discouraged?](https://stackoverflow.com/questions/48045401/why-are-multiple-instances-of-tk-discouraged)) – martineau Apr 07 '22 at 02:34

0 Answers0