Search code examples
pythontkinterfiledialog

Specify File path in tkinter File dialog


I have a file dialog to open a file, however, the file that I want to open is in a different directory than the program I wrote. The file dialog opens to the directory where I am. Is there a way to specify where the filedialog opens?

Here is the relevant code:

root = Tk()
root.fileName = tkFileDialog.askopenfilename()
f = open(root.fileName, 'r')

I tried adding the path that I want into the "askopenfilename" call, but that didn't work:

root.fileName = tkFileDialog.askopenfilename('/C:')

Solution

  • What you want is:

    root.fileName = tkFileDialog.askopenfilename(initialdir = "C:/<whatever>")
    

    This argument will allow you to specify the directory to which the window will open up.