We can open the operating system’s default open file dialog via Tkinter so the user can select file(s).
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.
123456
fromtkinterimportfiledialog# 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 91011121314
fromtkinterimportfiledialog# 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().
123456
# 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.
12345
# Get 1 or more filesselection=filedialog.askopenfilenames(filetypes=file_types)ifnotselection:print("Nothing was selected")