Choosing files and directories
File dialogs allow users to select one or multiple files from the filesystem. In Tkinter, these functions are declared in the tkinter.filedialog
module, which also includes dialogs for choosing directories. It also lets you customize the behavior of a new dialog, such as filtering the files by their extension or choosing the initial directory displayed by the dialog.
Getting ready
Our application will contain two buttons. The first will be labeled Choose file
, and it will display a dialog to select a file. By default, it will only show files with the .txt
extension:

The second button will be Choose directory
, and it will open a similar dialog to select a directory:

Both buttons will print the full path to the selected file or directory, and will not perform any action if the dialog is canceled.
How to do it...
The first button of our application will trigger a call to the askopenfilename
function, whereas the second one will call the askdirectory
function:
import...