- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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 get the absolute path of a file using tkFileDialog(Tkinter)?
Tkinter is a standard Python library that is used to create and develop functional and featured applications. It has a variety of inbuilt functions, modules, and packages that can be used for constructing the logic of the application.
The tkFileDialog is an inbuilt module available in the Tkinter library which is useful for interacting with the system files and directories. However, once we select a particular file in the read mode using tkFileDialog, potentially it can be used further to process the information available in the file.
If you want to access the absolute path of the file when it gets loaded in the application, you can use the available function of OS module, i.e., os.path.abspath(file.name) function. This function will return the absolute path of the file which can be stored in a variable to display in the window or screen.
# Import the required Libraries from tkinter import * from tkinter import ttk, filedialog from tkinter.filedialog import askopenfile import os # Create an instance of tkinter frame win = Tk() # Set the geometry of tkinter frame win.geometry("700x350") def open_file(): file = filedialog.askopenfile(mode='r', filetypes=[('Python Files', '*.py')]) if file: filepath = os.path.abspath(file.name) Label(win, text="The File is located at : " + str(filepath), font=('Aerial 11')).pack() # Add a Label widget label = Label(win, text="Click the Button to browse the Files", font=('Georgia 13')) label.pack(pady=10) # Create a Button ttk.Button(win, text="Browse", command=open_file).pack(pady=20) win.mainloop()
When we run the code, it will first display the following window −
Now, click the "Browse" button and select a Python file from the Explorer. It will show the absolute path of the file you selected.
- Get Absolute path of a file in Java
- Get the absolute path for the directory or file in Java
- Java Program to get the File object with the absolute path for the directory or file
- How to specify the file path in a tkinter filedialog?
- Get an Absolute Filename Path from a Relative Filename Path in Java
- Get an Absolute Filename Path from a Relative Filename with Path in Java
- How to get file name from a path in PHP?
- How to get left substring in MySQL from a column with file path? Display the entire file path string excluding the file name?
- Get the name of the file and path in Java
- How to get stat of a file using Python?
- How to get the last dirname/filename in a file path argument in Bash?
- How to get the absolute coordinates of a view in Android?
- Get the path of the file selected in the JFileChooser component with Java
- How to extract a part of the file path (a directory) in Python?