top of page
  • Writer's pictureVijithkumar V

askdirectory function of the tkinter library.

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

  1. 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.

  2. Then we create an instance of the Tk class. Here, the root is an object of the type <class '[tkinter.Tk](<http://tkinter.tk/>)'>.

  3. 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.

  4. 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()

12 views0 comments
  • Twitter Round
  • b-facebook

© 2035 by Z-Photography. Powered and secured by Wix

PHONE:
+91 9645304093

EMAIL:
thelifesciencehub2023@gmail.com
Subscribe to our website and receive updates!

Thanks for submitting!

Lifescience, C/o Vijithkumar, Dept. of Biotechnology,

Manonmaniam Sundaranar University, Tirunelveli, Tamil Nadu, India, PIN: 627012.

bottom of page