Add a option to delete each input folder after each output of that folder is finished here is code import os
import shutil
import threading
from tkinter import (
Tk,
Button,
Label,
filedialog,
messagebox,
StringVar,
)
from tkinter.ttk import Progressbar, Combobox
from concurrent.futures import ThreadPoolExecutor
Certainly! To add an option that allows users to delete each input (source) folder after processing its files, you'll need to make the following modifications to your existing code:
Add a Checkbox to the UI:
Introduce a checkbox that users can select if they want the source folders to be deleted after processing.
Modify the Processing Logic:
Update the process_files method to handle processing each source folder individually.
After processing the files in a source folder, check if the delete option is enabled and delete the folder accordingly.
Below is the updated code with these enhancements:
python
import os
import shutil
import threading
from tkinter import (
Tk,
Button,
Label,
filedialog,
messagebox,
StringVar,
BooleanVar,
Checkbutton,
)
from tkinter.ttk import Progressbar, Combobox
from concurrent.futures import ThreadPoolExecutor
class ImageRenamerCombinerGUI:
def __init__(self, root):
self.root = root
self.root.title("Image Renamer & Combiner")
self.root.geometry("500x450") # Increased height to accommodate new widgets
self.root.resizable(False, False)
self.source_folders = []
self.destination_folder = ""
self.mode = StringVar()
self.prefix = StringVar()
self.delete_source = BooleanVar() # Variable for delete option
# Source Folders Selection
self.btn_select_sources = Button(
root, text="Select Source Folders", command=self.select_source_folders
)
self.btn_select_sources.pack(pady=10)
self.lbl_sources = Label(root, text="No source folders selected.")
self.lbl_sources.pack()
# Destination Folder Selection
self.btn_select_destination = Button(
root, text="Select Destination Folder", command=self.select_destination_folder
)
self.btn_select_destination.pack(pady=10)
self.lbl_destination = Label(root, text="No destination folder selected.")
self.lbl_destination.pack()
# Mode Selection
self.lbl_mode = Label(root, text="Select Renaming Mode:")
self.lbl_mode.pack(pady=5)
self.cmb_mode = Combobox(
root,
textvariable=self.mode,
state="readonly",
values=[
"Add Custom Prefix",
"Sequential Numbering",
"Prefix Based on Folder",
],
)
self.cmb_mode.current(0)
self.cmb_mode.pack(pady=5)
self.cmb_mode.bind("<<ComboboxSelected>>", self.on_mode_change)
# Prefix Entry (Visible only for "Add Custom Prefix")
self.create_prefix_entry()
# Delete Source Folders Checkbox
self.chk_delete_source = Checkbutton(
root,
text="Delete Source Folders After Processing",
variable=self.delete_source
)
self.chk_delete_source.pack(pady=10)
# Combine and Rename Button
self.btn_start = Button(
root, text="Start Processing", command=self.start_processing
)
self.btn_start.pack(pady=10)
# Progress Bar
self.progress = Progressbar(root, orient="horizontal", length=400, mode="determinate")
self.progress.pack(pady=10)
def create_prefix_entry(self):
"""Creates or destroys the prefix entry widget based on the selected mode."""
# If 'Add Custom Prefix' is selected, show the prefix entry
if self.mode.get() == "Add Custom Prefix":
if not hasattr(self, 'lbl_prefix') or self.lbl_prefix is None:
self.lbl_prefix = Label(self.root, text="Enter Prefix:")
self.lbl_prefix.pack(pady=5)
from tkinter import Entry
self.prefix_entry_widget = Entry(self.root, textvariable=self.prefix, width=30)
self.prefix_entry_widget.pack(pady=5)
else:
# If previously created, destroy the prefix entry
if hasattr(self, 'prefix_entry_widget') and self.prefix_entry_widget:
self.prefix_entry_widget.destroy()
self.prefix_entry_widget = None
if hasattr(self, 'lbl_prefix') and self.lbl_prefix:
self.lbl_prefix.destroy()
self.lbl_prefix = None
def on_mode_change(self, event):
"""Handles the UI changes when the renaming mode is changed."""
self.create_prefix_entry()
def select_source_folders(self):
"""Allows the user to select multiple source folders."""
folder = filedialog.askdirectory(mustexist=True, title="Select a Source Folder")
if folder:
if folder not in self.source_folders:
self.source_folders.append(folder)
self.lbl_sources.config(text=f"Selected {len(self.source_folders)} source folder(s).")
else:
messagebox.showinfo("Duplicate Folder", "This folder has already been selected.")
# Ask if the user wants to select another folder
another = messagebox.askyesno("Select Another", "Do you want to select another source folder?")
if another:
self.select_source_folders()
def select_destination_folder(self):
"""Allows the user to select the destination folder."""
folder = filedialog.askdirectory(mustexist=True, title="Select Destination Folder")
if folder:
self.destination_folder = folder
self.lbl_destination.config(text=f"Destination: {self.destination_folder}")
def start_processing(self):
"""Starts the processing in a separate thread."""
if not self.source_folders:
messagebox.showwarning("No Source Folders", "Please select source folders first.")
return
if not self.destination_folder:
messagebox.showwarning("No Destination Folder", "Please select a destination folder.")
return
if self.mode.get() == "Add Custom Prefix" and not self.prefix.get():
messagebox.showwarning("No Prefix", "Please enter a prefix for renaming.")
return
# Disable the start button to prevent multiple clicks
self.btn_start.config(state="disabled")
# Start the processing in a separate thread
threading.Thread(target=self.process_files, daemon=True).start()
def process_files(self):
"""Processes the files based on the selected mode."""
try:
total_files = 0
renamed_files_all = []
# First, calculate the total number of files for the progress bar
for src_folder in self.source_folders:
for root_dir, _, files in os.walk(src_folder):
for file in files:
if self.is_image_file(file):
total_files += 1
if total_files == 0:
messagebox.showinfo("No Images Found", "No image files were found in the selected source folders.")
self.reset_ui()
return
# Initialize progress bar
self.progress["maximum"] = total_files
self.progress["value"] = 0
current_progress = 0
# Determine renaming strategy once
renaming_strategy = self.get_renaming_strategy()
# Process each source folder individually
for src_folder in self.source_folders:
file_operations = []
# Gather image files in the current source folder
for root_dir, _, files in os.walk(src_folder):
for file in files:
if self.is_image_file(file):
src_file = os.path.join(root_dir, file)
file_operations.append(src_file)
if not file_operations:
continue # Skip if no image files in this folder
# Apply renaming strategy
renamed_files = renaming_strategy(file_operations, src_folder)
renamed_files_all.extend(renamed_files)
# Copy files to destination folder
with ThreadPoolExecutor(max_workers=os.cpu_count() or 4) as executor:
futures = []
for src, dest in renamed_files:
futures.append(executor.submit(self.copy_file, src, dest))
for future in futures:
future.result() # To catch exceptions if any
current_progress += 1
self.progress["value"] = current_progress
self.root.update_idletasks()
# After processing the current folder, delete it if the option is selected
if self.delete_source.get():
try:
shutil.rmtree(src_folder)
print(f"Deleted source folder: {src_folder}")
except Exception as e:
messagebox.showerror("Deletion Error", f"Failed to delete {src_folder}: {e}")
messagebox.showinfo("Success", f"Successfully processed {total_files} images into {self.destination_folder}.")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
finally:
self.reset_ui()
def get_renaming_strategy(self):
"""Returns the appropriate renaming function based on the selected mode."""
if self.mode.get() == "Add Custom Prefix":
return self.add_custom_prefix
elif self.mode.get() == "Sequential Numbering":
return self.sequential_numbering
elif self.mode.get() == "Prefix Based on Folder":
return self.prefix_based_on_folder
else:
raise ValueError("Invalid renaming mode selected.")
def add_custom_prefix(self, file_list, src_folder):
"""Adds a custom prefix to each file."""
prefix = self.prefix.get()
renamed = []
for src in file_list:
filename = os.path.basename(src)
new_filename = f"{prefix}{filename}"
dest = os.path.join(self.destination_folder, new_filename)
renamed.append((src, dest))
return renamed
def sequential_numbering(self, file_list, src_folder):
"""Renames files with sequential numbering."""
renamed = []
# Generate a unique prefix based on the source folder to avoid filename conflicts
folder_identifier = os.path.basename(src_folder).replace(" ", "_") + "_"
count = 0
for src in sorted(file_list):
ext = os.path.splitext(src)[1]
new_filename = f"{folder_identifier}{count:05d}{ext}"
dest = os.path.join(self.destination_folder, new_filename)
renamed.append((src, dest))
count += 1
return renamed
def prefix_based_on_folder(self, file_list, src_folder):
"""Prefixes filenames based on their source folder name."""
renamed = []
folder_name = os.path.basename(src_folder)
for src in file_list:
filename = os.path.basename(src)
new_filename = f"{folder_name}_{filename}"
dest = os.path.join(self.destination_folder, new_filename)
renamed.append((src, dest))
return renamed
def copy_file(self, src, dest):
"""Copies a file from src to dest."""
os.makedirs(os.path.dirname(dest), exist_ok=True)
shutil.copy2(src, dest)
@staticmethod
def is_image_file(filename):
"""Checks if a file is an image based on its extension."""
image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff', '.webp')
return filename.lower().endswith(image_extensions)
def reset_ui(self):
"""Resets the UI elements after processing."""
self.btn_start.config(state="normal")
self.progress["value"] = 0
def main():
root = Tk()
app = ImageRenamerCombinerGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
BooleanVar: This variable holds the state of the checkbox (checked or unchecked).
Checkbutton: A checkbox is added below the prefix entry, allowing users to select if they want the source folders deleted after processing.
Modified process_files Method:
Processing Each Source Folder Individually:
The original code collected all image files from all source folders before processing. To handle deletion after each folder's processing, the code now iterates over each source folder one by one.
Renaming Strategy:
A helper method get_renaming_strategy determines which renaming function to use based on the selected mode.
Copying and Progress Update:
Files from each source folder are processed and copied to the destination. The progress bar is updated accordingly.
Deleting Source Folder:
After processing each source folder, the code checks if the delete option is enabled (self.delete_source.get()). If so, it attempts to delete the source folder using shutil.rmtree. Error handling ensures that any issues during deletion are communicated to the user.
python
Additional Recommendations
Backup Source Folders: Deleting source folders is irreversible. It might be prudent to prompt the user for confirmation before deletion or ensure that the deletion option is clearly communicated.
Logging: Consider adding logging to track processed files and any issues during processing or deletion. This can be helpful for troubleshooting.
Progress Indication: Currently, the progress bar updates based on the total number of files. You might also want to indicate which folder is currently being processed for better user experience.
Validation Before Deletion: Before deleting a folder, ensure that all files have been successfully copied to the destination. Although the current implementation waits for all copy operations to complete, additional checks can provide more assurance.
Final Thoughts
With these modifications, your application now provides users with the flexibility to delete source folders after processing, enhancing its functionality. Ensure thorough testing, especially the deletion feature, to prevent accidental data loss.
def process_files(self):
"""Processes the files based on the selected mode."""
try:
total_files = 0
renamed_files_all = []
# First, calculate the total number of files for the progress bar
for src_folder in self.source_folders:
for root_dir, _, files in os.walk(src_folder):
for file in files:
if self.is_image_file(file):
total_files += 1
if total_files == 0:
messagebox.showinfo("No Images Found", "No image files were found in the selected source folders.")
self.reset_ui()
return
# Initialize progress bar
self.progress["maximum"] = total_files
self.progress["value"] = 0
current_progress = 0
# Determine renaming strategy once
renaming_strategy = self.get_renaming_strategy()
# Process each source folder individually
for src_folder in self.source_folders:
file_operations = []
# Gather image files in the current source folder
for root_dir, _, files in os.walk(src_folder):
for file in files:
if self.is_image_file(file):
src_file = os.path.join(root_dir, file)
file_operations.append(src_file)
if not file_operations:
continue # Skip if no image files in this folder
# Apply renaming strategy
renamed_files = renaming_strategy(file_operations, src_folder)
renamed_files_all.extend(renamed_files)
# Copy files to destination folder
with ThreadPoolExecutor(max_workers=os.cpu_count() or 4) as executor:
futures = []
for src, dest in renamed_files:
futures.append(executor.submit(self.copy_file, src, dest))
for future in futures:
future.result() # To catch exceptions if any
current_progress += 1
self.progress["value"] = current_progress
self.root.update_idletasks()
# After processing the current folder, delete it if the option is selected
if self.delete_source.get():
try:
shutil.rmtree(src_folder)
print(f"Deleted source folder: {src_folder}")
except Exception as e:
messagebox.showerror("Deletion Error", f"Failed to delete {src_folder}: {e}")
messagebox.showinfo("Success", f"Successfully processed {total_files} images into {self.destination_folder}.")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
finally:
self.reset_ui()
Added Helper Method get_renaming_strategy:
python
def get_renaming_strategy(self):
"""Returns the appropriate renaming function based on the selected mode."""
if self.mode.get() == "Add Custom Prefix":
return self.add_custom_prefix
elif self.mode.get() == "Sequential Numbering":
return self.sequential_numbering
elif self.mode.get() == "Prefix Based on Folder":
return self.prefix_based_on_folder
else:
raise ValueError("Invalid renaming mode selected.")
This method determines which renaming function to use based on the user's selection. This makes the process_files method cleaner and more modular.
Adjusted Renaming Methods to Accept src_folder:
Updated the renaming methods to accept src_folder as a parameter. This allows for folder-specific processing, especially useful for naming strategies like "Sequential Numbering".
python
def add_custom_prefix(self, file_list, src_folder):
"""Adds a custom prefix to each file."""
prefix = self.prefix.get()
renamed = []
for src in file_list:
filename = os.path.basename(src)
new_filename = f"{prefix}{filename}"
dest = os.path.join(self.destination_folder, new_filename)
renamed.append((src, dest))
return renamed
def sequential_numbering(self, file_list, src_folder):
"""Renames files with sequential numbering."""
renamed = []
# Generate a unique prefix based on the source folder to avoid filename conflicts
folder_identifier = os.path.basename(src_folder).replace(" ", "_") + "_"
count = 0
for src in sorted(file_list):
ext = os.path.splitext(src)[1]
new_filename = f"{folder_identifier}{count:05d}{ext}"
dest = os.path.join(self.destination_folder, new_filename)
renamed.append((src, dest))
count += 1
return renamed
def prefix_based_on_folder(self, file_list, src_folder):
"""Prefixes filenames based on their source folder name."""
renamed = []
folder_name = os.path.basename(src_folder)
for src in file_list:
filename = os.path.basename(src)
new_filename = f"{folder_name}_{filename}"
dest = os.path.join(self.destination_folder, new_filename)
renamed.append((src, dest))
return renamed
Sequential Numbering Adjustment: To prevent filename conflicts when multiple folders are being processed, a folder_identifier is prepended to each filename.
Enhanced the UI Layout:
Adjusted the window height to accommodate the new checkbox without overlapping other widgets.
python
self.root.geometry("500x450") # Increased height to accommodate new widgets
Improved Prefix Entry Handling:
Fixed issues related to the prefix entry widget by ensuring it properly creates and destroys the entry field based on the selected mode.
Error Handling for Deletion:
Added error handling to inform the user if a source folder couldn't be deleted.
python
except Exception as e:
messagebox.showerror("Deletion Error", f"Failed to delete {src_folder}: {e}")