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.

Example

# 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()

Output

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.

Updated on: 18-Jun-2021

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements