72

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?

3 Answers 3

120

It appears that tkFileDialog.askdirectory should work. documentation

Sign up to request clarification or add additional context in comments.

1 Comment

the documentation for the askdirectory only seems to have information around a Python 2.7 version. Is there not a version 3?
45

This code may be helpful for you.

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

1 Comment

I've just been researching this for a bit, so I recognize the root.withdraw() as a solution for this question: stackoverflow.com/questions/9319317/… - where they want to know how to keep the root window closed for a command line program.
5

Go with this code First, select the directory for creating a new file

import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()
# file_path = filedialog.askopenfilename()
file_path = filedialog.askdirectory()

new_file = input("Name file\n")
open_file = open(f"{file_path}\%s.py" % new_file, 'w')

in my case

i created (ok.py) file in ppppp directory

path is: PS C:\Users\demo\Desktop\ppppp\ok.py

enter image description here

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.