Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add multiple extensions in one filetypes mac - tkinter/filedialog/askopenfilename

I am trying to use tkinter.filedialog to choose the file in Mac.

It works fine with one filetype in this way:

filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx")])

However, I want to choose either xlsx or xls files. I searched and found a question filedialog, tkinter and opening files. I use the similar way but it does not work with Mac if I change to this:

filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx; *.xls")])

How should I change to choose either xlsx or xls files in the file dialog?

like image 827
Joe Avatar asked Jun 07 '17 04:06

Joe


1 Answers

It seems that you must separate the wildcard patterns with a space rather than ; (verified on Python 3.5.1):

from tkinter import filedialog

# add `, initialdir="..."` to set the initial directory shown in the dialog
filedialog.askopenfilename(filetypes=[("Excel files", ".xlsx .xls")])

Note:

  • While "*.xlsx *.xls" would work too (at least on Windows and macOS), the initial * isn't necessary.[1]
  • Whether .* or *.* works (no filter) seems to be platform-dependent; omitting filetypes is the better option in that case.
  • Similarly, the behavior of matching part of the base filename - something like foo.txt or foo*.txt - appears to be platform-dependent: on Windows, these do work, with a prepended * (*foo.txt and *foo*.txt), whereas on macOS they seem to match nothing.

If the platform-dependent behaviors are instead / also linked to different tkinter versions, do let us know.


[1] Jakub Bláha reports that "*.xlsx *.xls" didn't actually work for him in Python 3.7.4 on Windows 10 version 1903 (though I don't see the same problem); to be safe, omit the * if not needed.

like image 83
mklement0 Avatar answered Sep 23 '22 01:09

mklement0