14
votes

I'm using OS X. I'm double clicking my script to run it from Finder. This script imports and runs the function below.

I'd like the script to present a Tkinter open file dialog and return a list of files selected.

Here's what I have so far:

def open_files(starting_dir):
    """Returns list of filenames+paths given starting dir"""
    import Tkinter
    import tkFileDialog

    root = Tkinter.Tk()
    root.withdraw()  # Hide root window
    filenames = tkFileDialog.askopenfilenames(parent=root,initialdir=starting_dir)
    return list(filenames)

I double click the script, terminal opens, the Tkinter file dialog opens. The problem is that the file dialog is behind the terminal.

Is there a way to suppress the terminal or ensure the file dialog ends up on top?

Thanks, Wes

5
Thank you I'll look into using that in the long term. Right now this program is very simple and is iterating quickly. I was looking to find a quick method of solving this annoyance. - Wes

5 Answers

14
votes

For anybody that ends up here via Google (like I did), here is a hack I've devised that works in both Windows and Ubuntu. In my case, I actually still need the terminal, but just want the dialog to be on top when displayed.

# Make a top-level instance and hide since it is ugly and big.
root = Tkinter.Tk()
root.withdraw()

# Make it almost invisible - no decorations, 0 size, top left corner.
root.overrideredirect(True)
root.geometry('0x0+0+0')

# Show window again and lift it to top so it can get focus,
# otherwise dialogs will end up behind the terminal.
root.deiconify()
root.lift()
root.focus_force()

filenames = tkFileDialog.askopenfilenames(parent=root) # Or some other dialog

# Get rid of the top-level instance once to make it actually invisible.
root.destroy()
6
votes

Use AppleEvents to give focus to Python. Eg:

import os

    os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''')
3
votes

I had this issue with the window behind Spyder:

root = tk.Tk()
root.overrideredirect(True)
root.geometry('0x0+0+0')
root.focus_force()
FT = [("%s files" % ftype, "*.%s" % ftype), ('All Files', '*.*')]
ttl = 'Select File'
File = filedialog.askopenfilename(parent=root, title=ttl, filetypes=FT)
root.withdraw()
1
votes

filenames = tkFileDialog.askopenfilenames(parent=root,initialdir=starting_dir)

Well parent=root is enough for making tkFileDialog on top. It simply means that your root is not on top, try making root on top and automatically tkFileDialog will take top of the parent.

0
votes

Try the focus_set method. For more, see the Dialog Windows page in PythonWare's An Introduction to Tkinter.