- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.