Why tkinter.filedialog.askdirectory isn't retu

2019-08-09 12:03发布

问题:

I'm trying to get the full path of a directory selected via tkinter.filedialog.askdirectory, but it only returns the path of the root folder, for example, selection the folder /root will return only '/', this seems strange, how to get it return the full path in python3.5?

import tkinter as tk from tkinter import filedialog

root = tk.Tk()
root.withdraw()
dirname = filedialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
if len(dirname ) > 0:
    print("You chose %s" % dirname)

回答1:

The filedialog.askdirectory() method returns an instance of filedialog.Directory class that need a PyObject command:

The mere selection of a folder does not represent a command, thus you do not get printed the folder you want. By double clicking on the folder you want represents a satisfying and coherent PyObject command resulting in the result you expect.

In simple words: you need to double click on the folder you want to open, then click Ok and not simply select it and click on Ok on the file open dialog window. Otherwise, you will get printed the path of the directory where you are now (initialdir = '/')