How to specify the file path in a tkinter filedialog?

Tkinter offers several built-in functions and class library methods to build components and user-actionable items of an application. filedialog is one of the tkinter modules that provides classes and library functions to create file/directory selection windows. You can use filedialog where you need to ask the user to browse a file or a directory from the system.

You can also specify the location of the directory from where a particular file should be picked up. To display the filedialog that starts from a particular location, use the initialdir = <location> argument in the static factory function askopenfilename(initialdir=<location>). This function creates a modal-like dialogbox and waits for the user's selection and returns the value of the selected file to the caller.


Let us create an application which asks the user to select a file from the system directory.

# Import required libraries
from tkinter import *
from tkinter import filedialog
from tkinter import ttk

# Create an instance of tkinter window
win = Tk()

# Create an instance of style class

def open_win_diag():
   # Create a dialog box
   f=open(win.file, 'r')

# Create a label widget
label=Label(win, text= "Click the button to browse the file", font='Arial 15 bold')
label.pack(pady= 20)

# Create a button to open the dialog box
button=ttk.Button(win, text="Open", command=open_win_diag)



Running the above code will display a window that contains two widgets.

The button widget triggers the file dialog box, asking the user to browse the file from the system.

We have specified "initialdir=C:/" in the askopenfilename() function. Hence, it opens the C Drive as the initial directory.