2

Using Python Tkinter I am trying to get the directory path of selected Folder. I do not want to load a file or navigate to a file but get the folder path like

enter image description here

How can I do this?

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

Update

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()
7
  • 2
    You added an update, but don't give any context. Is that update showing something you tried that failed? Something you tried that worked? Something else? Commented Mar 8, 2019 at 18:51
  • The code is doing same job as opening a file which is not what I want Commented Mar 8, 2019 at 21:19
  • I don't understand. The second one is asking both for a filename and then later a directory. I don't see what point you're trying to make. Commented Mar 8, 2019 at 21:27
  • I do not need file name. I jst want to navigate to the folder and Select it. Lets say I have a Folder which is Empty and I want to select it. Can you do this? Commented Mar 8, 2019 at 21:34
  • That's exactly what askdirectory() does. It lets you pick a directory. Commented Mar 8, 2019 at 21:36

2 Answers 2

5

You can use askdirectory from filedialog as follows:

from tkinter import filedialog #for Python 3
directory = filedialog.askdirectory()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for reply but this is not selecting any folder and just keeps looking to Open folders to select File inside. What I need is to stop after selecting a folder. Please take a look at update
5

Ok Looks like I find the solution on my own. Putting here which might help someone else in future.

import Tkinter, tkFileDialog
root = Tkinter.Tk()
root.withdraw()
dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
print(dirname)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.