Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I get Tkinter askopenfilename() to open on top of other windows?

Tags:

python

tkinter

tk

I am running a script that prompts the user for a file. There is no gui except for the file browser that opens up. I have 2 options: browse for file, or select entire folder using askdirectory(). The latter opens on top of all other windows, but the first one opens under everything, I have to minimize other windows to find it.

Here is the method I'm using for these operations

from Tkinter import Tk
from tkFileDialog import askdirectory, askopenfilename

root = Tk()
root.withdraw()

self.inpath = askdirectory()  # To open entire folder
Path = askopenfilename()      # Open single file

root.destroy()   # This is the very last line in my main script.

This is everything Tk related in my code. askdirectory opens on top, askopenfilename doesn't.

Is there a way to force it to open on top?

like image 210
J_matts Avatar asked Aug 03 '15 01:08

J_matts


3 Answers

root.wm_attributes('-topmost', 1) did it for me. I found it in another SO thread to be honest :-).

like image 145
seesharp Avatar answered Nov 09 '22 22:11

seesharp


I had the same problem. For me it works with:

file = filedialog.askopenfilename(parent=root)

So, the file dialog gets in front of toplevel window without uncomment root.attributes("-topmost", True)

like image 22
Benaja Wächter Avatar answered Nov 09 '22 20:11

Benaja Wächter


I want to share that the following lines worked superbly in my case. But I had to use both window.wm_attributes('-topmost', 1) and window=parent to make this work, see below:

import tkinter as tk
from tkinter import filedialog
window = tk.Tk()
window.wm_attributes('-topmost', 1)
window.withdraw()   # this supress the tk window

   filename = filedialog.askopenfilename(parent=window,
                                  initialdir="",
                                  title="Select A File",
                                  filetypes = (("Text files", "*.txt"), ("All files", "*")))
# Here, window.wm_attributes('-topmost', 1) and "parent=window" argument help open the dialog box on top of other windows
like image 29
Ashok Avatar answered Nov 09 '22 20:11

Ashok