Tkinter file pattern is installed in the file dialog

To get the set of expected files with the given extensions in the file dialog box, I saw written patterns in several places like ('label','pattern'), moreover, the pattern was on the same line. However, the following does not 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 
+4
source share
3 answers

If you are trying to associate two or more suffixes with the same file type (for example: "image files"), there are several ways to do this.

declare each suffix separately

You can specify each suffix on a separate line. They will be combined into one item in the drop-down 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')),
           ])
+3

('.png', '.jpg')

 ('image files', ('.png', '.jpg')),
+1
import tkinter
options = {}
options['defaultextension'] = '.txt'
options['filetypes'] = [('all files', '.*'), ('text files', '.txt'),('asc files', '.asc')]
options['initialdir'] = '.'
file_open = tkinter.filedialog.askopenfile(mode='r', **options)
-2

Source: https://habr.com/ru/post/1659111/


All Articles