Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a directory and store the location using tkinter in Python

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?

like image 774
Brad Conyers Avatar asked Jul 02 '12 14:07

Brad Conyers


People also ask

How do I select a directory in Python?

To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .

Does Tkinter have drag and drop?

Drag and Drop refers to moving widget while holding left click pressed. One can drag the widget or object in the x-axis or y-axis. As per the official documentation to enable an object to be dragged, It is necessary to bind an event to a callback function.

What does Mainloop () do in Tkinter?

mainloop() tells Python to run the Tkinter event loop. This method listens for events, such as button clicks or keypresses, and blocks any code that comes after it from running until you close the window where you called the method.


1 Answers

It appears that tkFileDialog.askdirectory should work. documentation

like image 115
mgilson Avatar answered Oct 19 '22 06:10

mgilson