0

I am using Tkinter's tkFileDialog package in some python code. The following command prompts the user to select a file with the ability to change the filetype between "csv" or "any".

tkFileDialog.askopenfilename(filetypes=[('csv files', '*.csv'), ('all 
    files', '*.*')],)

On Windows 10, this works as expected, but on OSX10.12.6, the filetype dropdown isn't available. It only allows selection of csv files, with no option to change the file type. How can I get this to work properly? My only idea is that tcl 8.6 on OSX is behaving differently than tcl 8.5 on windows.

1 Answers1

1

That's correct. The actual native file dialog on OSX doesn't support file type selection. A small number of applications enhance it to add that capability, but Tk doesn't, just like many other applications. This is because the OS style guide specifies to not do that.

If you really need file type selection, use the script-implemented version of the dialogs; they're cross-platform (and what is always used on Unix/X11 platforms). Unfortunately, they're not specially mapped to Python calls; you'll need to use the raw calling interface. (See How to Call TCL Procedure using Python for what the .tk.eval method does; it's not well documented, but it is exactly what you need.)

# Root context object
root = tkinter.Tk()

# The filetypes *IN TCL FORMAT*
filetypes = "{{csv files} *.csv} {{all files} *}"

# The actual call; note that that that's a very unusual command name by Tcl standards!
# 
filename = root.tk.eval('::tk::dialog::file:: open -filetypes {' + filetypes + '}')

# Fix up the result; empty string means "no file selected"
if filename == "":
    filename = None

Sorry this is messy, and it definitely won't look or feel native on OSX, but it should at least work…

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215