3

I'd like to accept certain file, config.cfg, in tkinter askopenfilename dialog and here is my code.

mod_config_path = tkinter.filedialog.askopenfilename(parent=None, 
                                                     title="Select config.cfg file", 
                                                     initialdir=steamapps, 
                                                     filetypes=[("config.cfg", "config.cfg")])

The problem is, filetypes=[("config.cfg", "config.cfg")] doesn't do what I meant to do.

I wanted to accept only config.cfg file, not misc_config.cfg or otherconfig.cfg that ends with config.cfg. But as shown below, it accepts *config.cfg file and misc_config.cfg file is also shown in the image.

image

So, what I want to do is, removing * in *config.cfg so that it only accepts config.cfg file.

I couldn't find any related answers around the internet and this is so disappointing...

tetratheta
  • 177
  • 1
  • 13
  • Is this possible? I think tkinter adds an additional `*` on first of whatever extension you give there. Maybe leave it like that and then use python to verify that the file selected is just `config.cfg` and not `somethingconfig.cfg`. – Delrius Euphoria Mar 26 '21 at 15:32
  • It seems to be an OS dependent behavior. I am using Linux and the provided code does exactly what is wanted: I see only "config.cfg", and not "misc_config.cfg" or "otherconfig.cfg" – j_4321 Mar 26 '21 at 15:48
  • @j_4321 I guess you are right. *On the Unix and Macintosh platforms, extensions are matched using glob-style pattern matching. On the Windows platform, extensions are matched by the underlying operating system.* [Source](https://tcl.tk/man/tcl8.6/TkCmd/getOpenFile.htm#M10) – Thingamabobs Mar 26 '21 at 16:13
  • You could consider to use `ctypes` and try to catch the [FileOK_Event](https://stackoverflow.com/a/37214623/13629335) but this seems to be too much work for me. If you just want to accept a special file, why dont you like to grap it programatically instead of a users choice? – Thingamabobs Mar 26 '21 at 16:27
  • Just for [reference](https://learn.microsoft.com/en-gb/dotnet/api/microsoft.win32.filedialog.filter?view=net-5.0) MS docs dosent discuss such a case. – Thingamabobs Mar 26 '21 at 16:29

1 Answers1

2

To summarize my comments as an answer:

The official docs of tcl for tk says:

On the Unix and Macintosh platforms, extensions are matched using glob-style pattern matching. On the Windows platform, extensions are matched by the underlying operating system.

So if you're under windows, either you write your own FileDialog or you try to catch the FileOK Event via ctypes and trigger a virtual event.

Alternatively you can follow @CoolCloud advice and verify file after the dialog.

Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46
Thingamabobs
  • 7,274
  • 5
  • 21
  • 54