In order to do so, we have to import the filedialog module from Tkinter. The File dialog module will help you open, save files or directories.
In order to open a file explorer, we have to use the method, askopenfilename(). This function creates a file dialog object.
Tkinter is a Python toolkit library used to build interfaces, design applications and create Graphical User Interfaces (GUIs). It originated from the Tcl programming language, which Python uses as a wrapper around Tk GUI Toolkit. Now it is used mostly with Python.
A file explorer is a tool that allows the user to navigate through all existing files present in the system for ease of access to files and open them without much difficulty. It offers a centralized database, where all file locations are stored.
By building the explorer in tkinter, we can find files much easier by integrating Python into the file explorer and customising its looks according to our requirements, a task that is not possible in a normal file explorer. Its API makes integration with the OS of the system seamless.
But, it has its limitations when it comes to building modern graphics and User-Interface (UI) design despite being able to create GUI applications. It generally has a very outdated look compared to modern UI design and widgets.
Tk provides functions to display dialogs for browsing files or folders on Windows, Linux (or any other Unix-based system) and macOS. In Python those functions are accessible through the tkinter.filedialog standard module. The most important ones are:
The askopenfilename() and askopenfilenames() functions display a dialog to open one or more files. askdirectory() does the same for browsing a folder (it is not possible to select more than one folder). asksaveasfilename() displays a dialog similar to the first two functions, but to save a file instead of opening it. We will see their differences in a moment.
On Windows and macOS these functions work internally with native dialogs provided by the OS, which ensures that you always get an up-to-date and modern tool for browsing files or folders. On the Microsoft system, Tk makes use of the IFileDialog, IFileOpenDialog and IFileSaveDialog native interfaces available starting with Windows Vista. On Windows XP and earlier, the GetOpenFileName() and GetSaveFileName() functions are used. The implementation can be seen in the tkWinDialog.c file of the Tk source code. On macOS, Tk also works with the NSOpenPanel and NSSavePanel native interfaces. The implementation is available in the tkMacOSXDialog.c file (written in Objective-C). On Unix systems the dialogs simulate the Windows (95) window and are written directly in Tcl in the tkfbox.tcl file.
All functions have a similar interface. They can be called without arguments and return a string (with the exception of askopenfilenames(), which returns a tuple of strings). For example, to display a dialog to open a file, use:
The dialog allows you to walk through the entire file system and select a file from it. The dialog texts are displayed in the language configured in the operating system. The path of the file selected by the user is returned as a string and stored, in this case, in the filename variable. If the user cancels or closes the dialog, the result is an empty string or tuple (depending on the operating system), so you'll probably want to do add a conditional after calling the function. Since both empty tuples and empty strings evaluate to False, it is not necessary to distinguish one case from the other. For example:
The askopenfilenames() function (note the "s" at the end) allows the user to select more than one file in the same folder. The result is in this case a tuple containing the paths of the selected files. Here, too, an empty string or tuple is returned when the dialog is cancelled.
The asksaveasfilename() function, on the other hand, is used to select a file that doesn't exist yet by typing its name into the textbox, typically to implement a file save feature. If the selected file already exists, the dialog displays a message to the user asking for his confirmation to replace the file. The return value has the same behavior as in askopenfilename().
The argument receives a tuple of 2-tuples. The first element of the inner tuples specifies the name of the file type that will be displayed to the user. The second can be a string or a tuple of strings containing the patterns to be used. For example, the *.txt string shows only files ending with .txt, while the ("*.py", "*.pyx") tuple displays files ending with both .py or .pyx. The *.* pattern is used to display files with any name and extension. When the filetypes argument is present, the dialog includes a dropdown list to show certain file types:
If intialdir is not specified, the initial path depends on the operating system. On Unix and macOS systems it is the current working directory, which is usually where your Python file is located. On Windows it is the last directory from which a file was successfully selected in that same application. On macOS sometimes the value of initialdir is ignored, depending on user settings.
In this article, we will make a simple file explorer with Python and its GUI Library Tkinter. We are adopting some features from the standard file explorer like the line-edit add the top, opening files with their usual program, and adding new files or folders.
As always, we import the needed libraries. We get the os module; this holds a special role since we do all the file interactions using it, such as getting all files in a directory or adding files. The ctypes import is optional; we simply enable high dpi (dots per inch). Calling the function in the last line will do just that. This will result in smoother graphics:
Next, we configure one column and one row. These two functions (grid_columnconfigure(), and grid_rowconfigure()) ensure that the second column and the second row expand. We will place our most essential widgets there, so they get a lot of space. Keep in mind that you can call these functions on any container widget.
Some of these functions have the parameter event=None and you notice that these event parameters aren't used in the function. This is because the functions are being called from two inputs. For one, there are called from buttons or menus, and these kinds of calls don't send any arguments to the supplied command functions.
Let's start with the pathChange() function. This will be called every time our path changes. We will bind a StringVar to it. It will update the list of files and folders and is responsible for displaying them.
We start by getting a list of all files and folders in a given path with the os.listdir() function. After that, we clear our list with its delete(start, end) method. Last but not least, we loop over every item in the directory list and insert it into the list with the insert(index, name) method.
The latter returns an array of all the selected items; that's why we only need the first item. We continue by joining with os.path.join() this picked file or folder with our current path, which is stored in a StringVar.
We check if the given path is a file with the os.path.isfile(path) function. If this turns out to be True, we call the os.startfile(path) with our path to open the file with its standard program. If it's False, we will set the StringVar to the new path, which triggers the pathChange() function we defined earlier and update the displayed files.
Here we will use the parent attribute of pathlib.Path() object to get the parent folder of our current one. After that, we just need to call the set(string) function on our StringVar and set it to this new path. This will once again trigger the pathChange() function.
It holds the window object, which is made in the following line with Toplevel(). Because it is a new window, it also has the title() and geometry() functions that set the name and dimensions of the window.
We define an Entry() that receives another StringVar which holds our new folder or file. This is also done to give the other function access to this function. In the end, we make a button that calls this function:
That's why we split the string by '.' and check if the resulting array has another length than one. A string will like file.txt will result to True, and something like folder/path is False. If it is a file name, we create it by simply opening the path with the built-in function open(path, mode) because if the file doesn't exist, it will make it. If it is a folder name, we need the os module and its mkdir() function to make the new directory.
In the end, we make an Entry() that holds the path we are currently in. For it to work correctly with the StringVar we have to set the textvariable parameter to our string variable. We also place this on the grid and set some padding with ipadx and ipady.
tkfilebrowser is an alternative to tkinter.filedialog that allows theuser to select files or directories. The GUI is written with tkinter butthe look is closer to GTK and the application uses GTK bookmarks (theone displayed in nautilus or thunar for instance). This filebrowsersupports new directory creation and filtype filtering.
askopenfilename that allow the selection of a single file
A Visual Studio Code extension with rich support for the Python language (for all actively supported Python versions), providing access points for extensions to seamlessly integrate and offer support for IntelliSense (Pylance), debugging (Python Debugger), formatting, linting, code navigation, refactoring, variable explorer, test explorer, and more!
These extensions are optional dependencies, meaning the Python extension will remain fully functional if they fail to be installed. Any or all of these extensions can be disabled or uninstalled at the expense of some features. Extensions installed through the marketplace are subject to the Marketplace Terms of Use.
c80f0f1006