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

拥有回忆 提交于 2019-12-17 06:36:28

问题


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?


回答1:


It appears that tkFileDialog.askdirectory should work. documentation




回答2:


This code may be helpful for you.

from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()


来源:https://stackoverflow.com/questions/11295917/how-to-select-a-directory-and-store-the-location-using-tkinter-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!