Reputation: 29
I programmed a small GUI with Tkinter where I ask the user for a directory to save certain images, via filedialog.askdirectory
. With that information, I am able to create a folder in that directory using os.mkdir()
, but I need to predefine its name ( i use a structure like year_month_day....).
Is there anyway in tkinter or using os library, where the user could define the name of the folder and then created? The idea is when the Windows folder browser is open, they could go the desired path and create a folder with the name they want
Upvotes: 0
Views: 2549
Reputation: 169
Is this what you want?
import os
from tkinter.filedialog import askdirectory
import tkinter.messagebox
import tkinter as tk
# Dir select
def selectPath():
path_ = askdirectory()
path.set(path_)
def create_file():
print("folder_name: ", folder.get())
print("path_name: ", path.get())
dirs = os.path.join(path.get(), folder.get())
if not os.path.exists(dirs):
os.makedirs(dirs)
tkinter.messagebox.showinfo('Tips:','Folder name created successfully!')
else:
tkinter.messagebox.showerror('Tips','The folder name exists, please change it')
root = tk.Tk()
root.title('Create folder')
root.geometry('400x380')
path = tk.StringVar() # Receiving user's file_path selection
folder = tk.StringVar() # Receiving user's folder_name selection
tk.Label(root,text = "Target path:").place(x=50, y= 250)
tk.Entry(root, textvariable = path).place(x=110, y= 250)
tk.Button(root, text = "Path select: ", command = selectPath).place(x=265, y= 250)
tk.Label(root,text = "Folder name:").place(x=50, y= 300)
tk.Entry(root,textvariable = folder).place(x=110, y= 300)
tk.Button(root, text = "Submit: ", command = create_file).place(x=265, y= 300)
root.mainloop()
path
and folder
variables are the path selected and the folder name created by the user.
It will look like this on my computer:
Upvotes: 1
Reputation: 1
from datetime import datetime
import os
from tkinter import filedialog
datestring = datetime.today().strftime('%Y-%m-%d') #Formats the date according to year,month,day.
#You can check out datetime for more info
default_folder = 'Adrain-{}'.format(datestring)
if os.path.exists(default_folder) == True: #Only creates a new folder when non-existing
pass
else:
os.mkdir(default_folder)
file_directory = filedialog.askdirectory(title = 'Select the target folder for saving
records', initialdir = default_folder)
Upvotes: 0
Reputation: 2685
You can do that by putting an input
widget called as a text widget. After inputting there a name of the folder and selecting the path using the filedialog
you can make a function which will create a directory.
def create_dir()
name = file_name.get() # took from the input
path = os.path.join(dir, name) # dir is a directory taken from the filedialog
Upvotes: 0