Let’s see how we can use the askdirectory function of the tkinter library to call a file-dialog box.
Why do we need to call a file-dialog box?
Imagine, we want to set a path variable - for example, let’s say for listing all the items in a particular folder or save a file to a particular folder. Normally, what we do is, we manually type down the path - either as a raw-string or as an escape sequence.
As a raw string as follows.
import os
path = r"D:\Movies"
items = os.listdir(path)
print(items)
Or, as escape sequence as follows.
import os
path = "D:\\Movies"
items = os.listdir(path)
print(items)
In both cases, the program executes the task. What if at every execution we need to set a different path variable?!
Here is where askdirectrory function of the tkinter library becomes useful. With askdirectory function invoked, we can simply select the folder- or file-path, and the path variable will be set.
Let’s look at the example below.
from tkinter import Tk
from tkinter.filedialog import askdirectory
root = Tk()
print(type(root))
path = askdirectory(parent=root, initialdir='D:/', title="select the directory")
print(path)
root.mainloop()
Let’s look at the code breakdown
For calling the file-dialog box, first of all, we need to import the Tk class from the tkinter library, and askdirectory function from the tkinter.filedialog.
Then we create an instance of the Tk class. Here, the root is an object of the type <class '[tkinter.Tk](<http://tkinter.tk/>)'>.
Next, we call the askdirectory function, with a set of parameters passed to it. The “parent” parameter specifies the Tk class instance that you want to associate the file-dialog box with. The “initialdir” parameter is set with a string argument that refers to the default path to a directory, which will be displayed when the file-dialog box opens. The “title” parameter represents the title of the file-dialog box.
The root.mainloop() ensures the main window is open for any keyboard or mouse event. Otherwise, if the file-dialogbox needs to be closed as soon as the path variable is set, then root.destroy() needs to be used instead of root.mainloop()
Comments