使用 Python Tkinter 我试图获取所选文件夹的目录路径。我不想加载文件或导航到文件,但获取文件夹路径,例如
我怎样才能做到这一点?
from Tkinter import *
from tkFileDialog import askopenfilename
def callback():
name= askopenfilename()
print name
errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)
mainloop()
Run Code Online (Sandbox Code Playgroud)
更新
from Tkinter import *
from tkFileDialog import askopenfilename
from tkinter import filedialog #for Python 3
def callback():
name= askopenfilename()
directory = filedialog.askdirectory()
print directory
errmsg = 'Error!'
Button(text='File Open', command=callback).pack(fill=X)
mainloop()
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用filedialog 中的askdirectory,如下所示:
from tkinter import filedialog #for Python 3
directory = filedialog.askdirectory()
Run Code Online (Sandbox Code Playgroud)
好吧,看来我自己找到了解决方案。放在这里可能会对将来的其他人有所帮助。
import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
print(dirname)
Run Code Online (Sandbox Code Playgroud)