Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to select a directory and store the location using Tkinter in Python?
Dialog boxes are essential components in GUI applications that enable user interaction. In Python's Tkinter, we can create file and directory selection dialogs using the filedialog module. This allows users to browse and select files or directories from their local system.
Selecting a File Directory
To select a directory (folder) instead of individual files, we use filedialog.askdirectory(). Here's how to create a simple directory selector ?
# Import the Tkinter library
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
# Create an instance of Tkinter frame
win = Tk()
win.title("Directory Selector")
win.geometry("750x300")
def select_directory():
directory_path = filedialog.askdirectory(title="Select a Directory")
if directory_path: # Check if user didn't cancel
result_label.config(text=f"Selected Directory: {directory_path}")
else:
result_label.config(text="No directory selected")
# Create UI elements
title_label = Label(win, text="Click the Button to Select a Directory",
font=('Arial', 18, 'bold'))
title_label.pack(pady=20)
select_button = ttk.Button(win, text="Select Directory", command=select_directory)
select_button.pack(pady=15)
# Label to display selected directory path
result_label = Label(win, text="", font=('Arial', 12),
wraplength=700, justify='left')
result_label.pack(pady=20)
win.mainloop()
Selecting Files with File Dialog
For selecting individual files, we use filedialog.askopenfilename() ?
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
win = Tk()
win.title("File Selector")
win.geometry("750x300")
def select_file():
file_path = filedialog.askopenfilename(
title="Select a File",
filetypes=[('Text files', '*.txt'),
('Python files', '*.py'),
('All files', '*.*')]
)
if file_path:
file_label.config(text=f"Selected File: {file_path}")
else:
file_label.config(text="No file selected")
Label(win, text="Click the Button to Select a File",
font=('Arial', 18, 'bold')).pack(pady=20)
ttk.Button(win, text="Select File", command=select_file).pack(pady=15)
file_label = Label(win, text="", font=('Arial', 12),
wraplength=700, justify='left')
file_label.pack(pady=20)
win.mainloop()
Storing Selected Path in Variable
You can store the selected directory or file path in a variable for later use ?
from tkinter import *
from tkinter import filedialog
class DirectorySelector:
def __init__(self):
self.selected_path = "" # Store path here
self.root = Tk()
self.root.title("Path Storage Example")
self.root.geometry("600x200")
self.setup_ui()
def setup_ui(self):
Label(self.root, text="Directory Path Storage Demo",
font=('Arial', 16, 'bold')).pack(pady=10)
Button(self.root, text="Select Directory",
command=self.select_and_store).pack(pady=10)
self.path_label = Label(self.root, text="No directory selected",
wraplength=500)
self.path_label.pack(pady=10)
Button(self.root, text="Show Stored Path",
command=self.show_stored_path).pack(pady=5)
def select_and_store(self):
path = filedialog.askdirectory()
if path:
self.selected_path = path # Store the path
self.path_label.config(text=f"Selected: {path}")
def show_stored_path(self):
if self.selected_path:
print(f"Stored path: {self.selected_path}")
else:
print("No path stored yet")
# Create and run the application
app = DirectorySelector()
app.root.mainloop()
Common File Dialog Methods
| Method | Purpose | Returns |
|---|---|---|
askdirectory() |
Select a directory | Directory path string |
askopenfilename() |
Select a single file | File path string |
askopenfilenames() |
Select multiple files | Tuple of file paths |
asksaveasfilename() |
Save file dialog | File path string |
Conclusion
Tkinter's filedialog module provides easy-to-use methods for directory and file selection. Use askdirectory() for folder selection and store the returned path in variables for further processing in your application.
