Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Create a py gui script that takes multiple folders with subs folder with images…

  1. User

    Create a py gui script that takes multiple folders with subs folder with images sequences and combines them into on folder of images based with each having selected folder prefix and its folder prefix then add all images into one folder making sure none overlap

  2. Assistant

    Certainly! Below is a Python script using Tkinter to create a GUI application that allows users to select multiple source folders, each containing subfolders with image sequences. The script will combine all images into a single destination folder, prefixing each image filename with its respective folder prefixes to avoid any naming conflicts.

    Features:

    • Select Multiple Source Folders: Choose multiple folders that contain subfolders with image sequences.
    • Select Destination Folder: Choose a single folder where all images will be combined.
    • Prefix Filenames: Automatically prefixes filenames with their main folder and subfolder names to prevent overlaps.
    • Progress Display: Shows progress during the file copying process.
    • Error Handling: Alerts the user in case of any issues during the process.

    Prerequisites:

    • Python 3.x
    • Ensure you have the necessary permissions to read from source folders and write to the destination folder.

    Script:

    import os
    import shutil
    from tkinter import (
        Tk,
        Button,
        Label,
        Listbox,
        END,
        MULTIPLE,
        filedialog,
        messagebox,
        StringVar,
    )
    from tkinter.ttk import Progressbar
    
    class ImageCombinerGUI:
        def __init__(self, root):
            self.root = root
            self.root.title("Image Sequence Combiner")
    
            self.source_folders = []
            self.destination_folder = ""
    
            # Source Folders Selection
            self.btn_select_sources = Button(
                root, text="Select Source Folders", command=self.select_source_folders
            )
            self.btn_select_sources.pack(pady=5)
    
            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=5)
    
            self.lbl_destination = Label(root, text="No destination folder selected.")
            self.lbl_destination.pack()
    
            # Start Button
            self.btn_start = Button(
                root, text="Combine Images", command=self.combine_images
            )
            self.btn_start.pack(pady=20)
    
            # Progress Bar
            self.progress = Progressbar(root, orient="horizontal", length=400, mode="determinate")
            self.progress.pack(pady=10)
    
        def select_source_folders(self):
            folders = filedialog.askdirectory(mustexist=True, title="Select Source Folders", multiple=True)
            if folders:
                # On some OS, folders might come as a tuple, ensure it's a list
                if isinstance(folders, str):
                    folders = [folders]
                self.source_folders = list(folders)
                self.lbl_sources.config(text=f"Selected {len(self.source_folders)} source folder(s).")
    
        def select_destination_folder(self):
            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 combine_images(self):
            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
    
            total_files = 0
            file_operations = []
    
            # Gather all image files with their new prefixed names
            for src_folder in self.source_folders:
                main_prefix = os.path.basename(src_folder)
                for subdir, _, files in os.walk(src_folder):
                    sub_prefix = os.path.basename(subdir)
                    for file in files:
                        if self.is_image_file(file):
                            total_files += 1
                            new_prefix = f"{main_prefix}_{sub_prefix}"
                            new_filename = f"{new_prefix}_{file}"
                            src_file = os.path.join(subdir, file)
                            dest_file = os.path.join(self.destination_folder, new_filename)
                            file_operations.append((src_file, dest_file))
    
            if total_files == 0:
                messagebox.showinfo("No Images Found", "No image files were found in the selected source folders.")
                return
    
            # Initialize progress bar
            self.progress["maximum"] = total_files
            self.progress["value"] = 0
    
            # Copy files
            for idx, (src, dest) in enumerate(file_operations, start=1):
                try:
                    shutil.copy2(src, dest)
                except Exception as e:
                    messagebox.showerror("Error", f"Failed to copy {src} to {dest}.\n\nError: {e}")
                    return
                self.progress["value"] = idx
                self.root.update_idletasks()
    
            messagebox.showinfo("Success", f"Successfully combined {total_files} images into {self.destination_folder}.")
    
        @staticmethod
        def is_image_file(filename):
            image_extensions = ('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tiff', '.webp')
            return filename.lower().endswith(image_extensions)
    
    def main():
        root = Tk()
        app = ImageCombinerGUI(root)
        root.geometry("450x300")
        root.resizable(False, False)
        root.mainloop()
    
    if __name__ == "__main__":
        main()
    

    How It Works:

    1. Selecting Source Folders:

      • Click the "Select Source Folders" button.
      • A dialog will appear allowing you to select multiple folders.
      • The selected folders are stored and displayed in the GUI.
    2. Selecting Destination Folder:

      • Click the "Select Destination Folder" button.
      • Choose a single folder where all images will be copied.
      • The selected destination is displayed in the GUI.
    3. Combining Images:

      • Click the "Combine Images" button to start the process.
      • The script traverses each source folder and its subdirectories.
      • For each image file found, it prefixes the filename with its main folder and subfolder names (e.g., MainFolder_SubFolder_image1.png).
      • The prefixed images are copied to the destination folder.
      • A progress bar indicates the copying progress.
      • Upon completion, a success message is displayed.

    Running the Script:

    1. Save the Script:

      • Save the above script to a file, for example, image_combiner.py.
    2. Run the Script:

      • Open a terminal or command prompt.
      • Navigate to the directory containing image_combiner.py.
      • Execute the script using Python:
        python image_combiner.py
        
      • Ensure that Python 3.x is installed and properly set in your system's PATH.
    3. Using the Application:

      • Follow the on-screen instructions to select source folders and the destination folder.
      • Click "Combine Images" to start the process.

    Notes:

    • Filename Prefixing: The script prefixes each image with its main folder and subfolder names separated by underscores. You can modify the new_prefix assignment in the script if you prefer a different naming convention.

    • Image File Types: The script currently handles common image file extensions. You can add or remove extensions in the is_image_file method as needed.

    • Error Handling: If the script encounters an error while copying a file, it will display an error message and halt the process. Ensure that the destination folder has sufficient permissions and storage space.

    • Progress Bar: The progress bar updates in real-time to reflect the copying progress. For large numbers of files, this provides visual feedback to the user.

    Feel free to customize and enhance the script according to your specific requirements!