How to make a new folder using askdirectory dialog in Tkinter?


To make a new folder using askdirectory dialog in Tkinter, we can take the following steps −

  • Import the required modules. filedialog module is required for askdirectory method. os module is required for makedirs method.

  • Create an instance of tkinter frame.

  • Set the size of the frame using win.geometry method.

  • Define a user-defined method "create_subfolder". Inside the method, call filedialog.askdirectory to select a folder and save the path in a variable, source_path.

  • We can use askdirectory method of filedialog to open a directory. Save the path of the selected directory in a 'path' variable.

  • Then, use os.path.join and makedirs to create a sub-folder inside the parent directory.

  • Create a button to call the create_subfolder method.

Example

# Import the required libraries
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import os

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window
win.geometry("700x350")

def create_subfolder():
   source_path = filedialog.askdirectory(title='Select the Parent Directory')
   path = os.path.join(source_path, 'Images')
   os.makedirs(path)

button1 = ttk.Button(win, text="Select a Folder", command=create_subfolder)

button1.pack(pady=5)

win.mainloop()

Output

When we execute the above code, it will first show the following window −

Now, click the "Select a Folder" button to select a parent folder. It will automatically create a sub-folder called "Images" in the selected parent folder.

Updated on: 26-Oct-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements