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 get a string from a tkinter filedialog in Python 3?
To interact with the filesystem in a tkinter application, you can use the tkinter.filedialog module. It provides various built-in functions to create file selection dialogs, with askopenfilename() being the most commonly used to get a file path as a string.
Basic File Selection Dialog
The simplest way to get a file path string is using askopenfilename() −
from tkinter import *
from tkinter import filedialog
# Create an instance of tkinter window
win = Tk()
win.geometry("700x300")
# Create a dialog to select a file
file_path = filedialog.askopenfilename(
initialdir="/",
title="Select a file",
filetypes=(("Text files", "*.txt"), ("All files", "*.*"))
)
# Display the selected file path
if file_path:
label = Label(win, text=f"Selected file: {file_path}", font='Courier 11 bold')
label.pack(pady=20)
else:
label = Label(win, text="No file selected", font='Courier 11 bold')
label.pack(pady=20)
win.mainloop()
Interactive File Selection with Button
A more user-friendly approach uses a button to trigger the file dialog −
from tkinter import *
from tkinter import filedialog
def select_file():
file_path = filedialog.askopenfilename(
initialdir="/",
title="Select a file",
filetypes=(("Python files", "*.py"), ("Text files", "*.txt"), ("All files", "*.*"))
)
if file_path:
result_label.config(text=f"Selected: {file_path}")
# Extract just the filename from full path
filename = file_path.split('/')[-1] # For Unix/Mac
# filename = file_path.split('\')[-1] # For Windows
filename_label.config(text=f"Filename: {filename}")
else:
result_label.config(text="No file selected")
filename_label.config(text="")
# Create main window
root = Tk()
root.title("File Dialog Example")
root.geometry("600x200")
# Create button to open file dialog
select_button = Button(root, text="Select File", command=select_file, font='Arial 12 bold')
select_button.pack(pady=20)
# Labels to display results
result_label = Label(root, text="No file selected yet", wraplength=500, font='Courier 10')
result_label.pack(pady=10)
filename_label = Label(root, text="", font='Courier 10 bold')
filename_label.pack(pady=5)
root.mainloop()
Different File Dialog Types
The filedialog module provides several functions for different purposes −
from tkinter import *
from tkinter import filedialog
root = Tk()
root.withdraw() # Hide the main window
# Open single file
single_file = filedialog.askopenfilename(title="Select one file")
print(f"Single file: {single_file}")
# Open multiple files
multiple_files = filedialog.askopenfilenames(title="Select multiple files")
print(f"Multiple files: {multiple_files}")
# Save file dialog
save_file = filedialog.asksaveasfilename(
defaultextension=".txt",
filetypes=[("Text files", "*.txt"), ("All files", "*.*")]
)
print(f"Save as: {save_file}")
# Select directory
directory = filedialog.askdirectory(title="Select a directory")
print(f"Directory: {directory}")
root.destroy()
Single file: /path/to/selected/file.txt
Multiple files: ('/path/to/file1.txt', '/path/to/file2.py')
Save as: /path/to/new_file.txt
Directory: /path/to/selected/directory
Common Parameters
| Parameter | Description | Example |
|---|---|---|
initialdir |
Starting directory | initialdir="/" |
title |
Dialog window title | title="Select file" |
filetypes |
File type filters | [("Text", "*.txt")] |
defaultextension |
Default file extension | defaultextension=".txt" |
Conclusion
Use filedialog.askopenfilename() to get a file path as a string. For better user experience, trigger the dialog with a button and handle the case when no file is selected. The function returns an empty string if the user cancels the dialog.
