File Dialog – Open file dialog

We can open the operating system’s default open file dialog via Tkinter so the user can select file(s).

img

The screenshot above is the open file dialog in Linux. It will look different in other operating systems.

First, we need to specify which file types to show to the user.

1
2
3
4
5
6
from tkinter import filedialog

# A Python list which has tuples in it.
file_types = [("Both PNG and JPG", ".png .jpg"),
                          ("PNG only", ".png"),
                          ("JPG only", ".jpg")]

Now that we know which file types we want the user to be able to select, let’s open the file dialog.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from tkinter import filedialog

# A Python list which has tuples in it.
file_types = [("Both PNG and JPG", ".png .jpg"),
                          ("PNG only", ".png"),
                          ("JPG only", ".jpg")]

# This will open the file dialog and allow
# the user to select 1 or more files.
selected_files = filedialog.askopenfilenames(filetypes=file_types)

print(selected_files)
# In this example, the user selected 2 files
> ('/home/user/background.png', '/home/user/sky.jpg')

To allow the user to only select 1 file, use the method: .askopenfilename() instead of .askopenfilenames().

1
2
3
4
5
6
# This will open the file dialog and allow
# the user to select 1 file.
one_selection = filedialog.askopenfilename(filetypes=file_types)

print(one_selection)
> /home/user/background.png

If the user clicks ‘Cancel’ or closes the dialog without choosing a file, it will evaluate to False, so you can check for False.

1
2
3
4
5
# Get 1 or more files
selection = filedialog.askopenfilenames(filetypes=file_types)

if not selection:
    print("Nothing was selected")