34

I am creating a GUI with a browse button which I only want to return the path. I've been looking at solutions using code like below.

Tkinter.Button(subframe, text = "Browse", command = self.loadtemplate, width = 10).pack()

   def loadtemplate(self): 
        filename = tkFileDialog.askopenfilename(filetypes = (("Template files", "*.tplate")
                                                             ,("HTML files", "*.html;*.htm")
                                                             ,("All files", "*.*") ))
        if filename: 
            try: 
                self.settings["template"].set(filename)
            except: 
                tkMessageBox.showerror("Open Source File", "Failed to read file \n'%s'"%filename)

However I know Tkinter has a built in askopenfilename which is a super easy one line of code for opening files. Is there some way to modify this to return the directory instead of a file? Is there a smaller option than the larger chunk of code I posted?

Cristian Ciupitu
  • 18,164
  • 7
  • 46
  • 70
Brad Conyers
  • 811
  • 4
  • 14
  • 21

2 Answers2

81

It appears that tkFileDialog.askdirectory should work. documentation

mgilson
  • 264,617
  • 51
  • 541
  • 636
20

This code may be helpful for you.

from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()
Mohammad Usman
  • 30,882
  • 16
  • 80
  • 78
Siva Madugula
  • 201
  • 2
  • 4
  • 2
    I've just been researching this for a bit, so I recognize the `root.withdraw()` as a solution for this question: https://stackoverflow.com/questions/9319317/quick-and-easy-file-dialog-in-python - where they want to know how to keep the root window closed for a command line program. – Michael S Mar 25 '18 at 02:38