Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tkinter file pattern set in a file dialog

Tags:

python

tkinter

To get the set of expected files with given extensions in a file dialog, I've seen in several places written patterns as ('label','pattern'), the pattern being in one string. However the following doesn't work

from tkinter import filedialog as fd
fd.askopenfilenames(
    title='Choose a file',
    filetypes=[('all files', '.*'),
               ('text files', '.txt'),
               ('image files', '.png;.jpg'), # nope,returns *.png;.jpg
               ('image files!', '*.png;*.jpg')]) # neither 
like image 523
Flint Avatar asked Oct 27 '16 19:10

Flint


People also ask

How do you display a file dialog for opening a file in Python?

Use the askopenfilename() function to display an open file dialog that allows users to select one file. Use the askopenfilenames() function to display an open file dialog that allows users to select multiple files.

What is Filedialog in Python?

Build A Paint Program With TKinter and Python filedialog is one of the tkinter modules that provides classes and library functions to create file/directory selection windows. You can use filedialog where you need to ask the user to browse a file or a directory from the system.


1 Answers

If you are trying to associate two or more suffixes with a single file type (eg: "image files"), there are a couple of ways to do it.

declare each suffix separately

You can specify each suffix on a separate line. They will be combined into one item in the dropdown list:

filenames = fd.askopenfilenames(
    title="Choose a file",
    filetypes=[('all files', '.*'),
               ('text files', '.txt'),
               ('image files', '.png'),
               ('image files', '.jpg'),
           ])

using a tuple

You can also specify them as a tuple:

filenames = fd.askopenfilenames(
    title="Choose a file",
    filetypes=[('all files', '.*'),
               ('text files', '.txt'),
               ('image files', ('.png', '.jpg')),
           ])
like image 83
Bryan Oakley Avatar answered Oct 22 '22 04:10

Bryan Oakley