3

I am trying to present the user with a file open dialog for files that fit a specific pattern. They are of the form prefix_*.suffix, where the asterisk represents a wildcard.

Here is a minimal example of how I assume this should be accomplished with TkInter:

from tkinter.filedialog import askopenfilename

my_dir = 'C:\\path\\to\\some\\directory'
pattern = (('File type', 'prefix_*.suffix'),)
title = 'Title'
my_file = askopenfilename(initialdir=my_dir, filetypes=pattern, title=title)

However, the resulting dialog box prepends a spurious wildcard to the front of my pattern, so that it now looks like *prefix_*.suffix. This is not what I expected.

TkInter AskOpenFileDialog Bug?

Am I doing something wrong? I can't find any decent documentation on how this interface in TkInter is supposed to work, so maybe it is more limited than I expected. If so, is there a builtin Python library that would support this specific use case?

In case if it is relevant to the question, I am on Windows 10 with a 32-bit install of Python.

Ryan
  • 169
  • 2
  • 6
  • Python does this by auto including a * at the first type of file, and when you put a comma, it makes it a new type of specified file. – Trooper Z Jul 26 '18 at 18:51
  • @TrooperZ If that were the case, I should be able to try \\prefix_\*.suffix, but that doesn't work. It just removes the backslash and prepends an asterisk. This seems to be TkInter-specific – Ryan Jul 26 '18 at 19:11

1 Answers1

3

The values in filetypes are interpreted as file extensions, not file patterns.

From the official tcl/tk documentation (tkinter is a thin wrapper around tcl/tk):

The filePatternList value given by the -filetypes option is a list of file patterns. Each file pattern is a list of the form typeName {extension ?extension ...?} ?{macType ?macType ...?}? typeName is the name of the file type described by this file pattern and is the text string that appears in the File types listbox. extension is a file extension for this file pattern.

It goes on to say this:

Due to the different pattern matching rules on the various platforms, to ensure portability, wild card characters are not allowed in the extensions, except as in the special extension “*”. Extensions without a full stop character (e.g. “~”) are allowed but may not work on all platforms.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Okay, this makes a lot more sense, I am coming from more of a Qt background where patterns are more of the norm. Out of curiosity, do you know why something like *_suffix.txt still works? Is that just a coincidence and not an intended use case? – Ryan Jul 27 '18 at 12:39