How to select a directory and store the location using Tkinter in Python?


We are familiar with dialog boxes and interacted with them in many types of applications. Such types of dialogs are useful in creating an application where user interaction is a prime need. We can use the dialog boxes to ask the user to select different types of files and then perform certain operations such as reading the file, writing to the file, etc. The dialog boxes can be created by using the filedialog Module in Python.

Example

In this example, we will create an application that will ask the user to select a file from the local directory and then will display the location of the directory with the help of Labels.

#Import the Tkinter library
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
#Create an instance of Tkinter frame
win= Tk()
#Define the geometry
win.geometry("750x250")
def select_file():
   path= filedialog.askopenfilename(title="Select a File", filetype=(('text files''*.txt'),('all files','*.*')))
   Label(win, text=path, font=13).pack()
#Create a label and a Button to Open the dialog
Label(win, text="Click the Button to Select a File", font=('Aerial 18 bold')).pack(pady=20)
button= ttk.Button(win, text="Select", command= select_file)
button.pack(ipadx=5, pady=15)
win.mainloop()

Output

Running the above code will display a window that contains a button to select the file from the directory and display the file location on the window.

Now, select any file from the local directory and then, it will display the location of the file in a Label widget.

Updated on: 22-Apr-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements