import os
import shutil
import tkinter as tk
from tkinter import filedialog, simpledialog
from collections import defaultdict

def select_directory():
    dir_path = filedialog.askdirectory()
    dir_label.config(text=dir_path)

def start_grouping():
    dir_path = dir_label.cget("text")
    if os.path.isdir(dir_path):
        group_files_by_segment(dir_path)

def group_files_by_segment(dir_path):
    compare_length = compare_slider.get()
    files = [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))]
    grouped_files = defaultdict(list)

    for file in files:
        if ':' in file:
            segment = file.split(':', 1)[1].strip()
        else:
            segment = file.strip()

        comparison_key = segment[:compare_length]

        # Add the file to a group with a shared comparison key
        grouped_files[comparison_key].append(file)

    folder_listbox.delete(0, tk.END)
    
    sorted_grouped_keys = sorted(grouped_files)  # Sort keys to display
    for group_name in sorted_grouped_keys:
        folder_listbox.insert(tk.END, group_name)

    folder_listbox.grouped_files = grouped_files

def show_folder_content(event):
    widget = event.widget
    if not widget.curselection():
        return
    index = widget.curselection()[0]
    group_name = widget.get(index)
    grouped_files = getattr(folder_listbox, 'grouped_files', {})

    filenames_listbox.delete(0, tk.END)
    for file in grouped_files.get(group_name, []):
        filenames_listbox.insert(tk.END, file)

def rename_folder(event):
    widget = event.widget
    if not widget.curselection():
        return
    index = widget.curselection()[0]
    old_name = widget.get(index)

    new_name = simpledialog.askstring("Rename Folder", f"Enter new name for {old_name}:")
    if new_name:
        grouped_files = getattr(folder_listbox, 'grouped_files', {})
        if old_name in grouped_files:
            grouped_files[new_name] = grouped_files.pop(old_name)

        widget.delete(index)
        widget.insert(index, new_name)

def apply_folders():
    dir_path = dir_label.cget("text")
    grouped_files = getattr(folder_listbox, 'grouped_files', {})

    for folder_name, file_list in grouped_files.items():
        folder_path = os.path.join(dir_path, folder_name)
        os.makedirs(folder_path, exist_ok=True)

        for f in file_list:
            src_file = os.path.join(dir_path, f)
            dest_file = os.path.join(folder_path, f)
            shutil.move(src_file, dest_file)

app = tk.Tk()
app.title("File Grouper")
app.geometry("900x500")

control_frame = tk.Frame(app)
control_frame.pack(side=tk.TOP, fill=tk.X)

select_button = tk.Button(control_frame, text="Select Directory", command=select_directory)
select_button.pack(side=tk.LEFT)

dir_label = tk.Label(control_frame, text="No directory selected")
dir_label.pack(side=tk.LEFT, padx=10)

start_button = tk.Button(control_frame, text="Start Grouping", command=start_grouping)
start_button.pack(side=tk.LEFT, padx=10)

compare_slider = tk.Scale(control_frame, from_=1, to=20, orient=tk.HORIZONTAL, label="Comparison Characters")
compare_slider.set(5)
compare_slider.pack(side=tk.LEFT, padx=10)

apply_button = tk.Button(control_frame, text="Apply Changes", command=apply_folders)
apply_button.pack(side=tk.LEFT, padx=10)

listboxes_frame = tk.Frame(app)
listboxes_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

folder_listbox = tk.Listbox(listboxes_frame, width=30)
folder_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
folder_listbox.bind('<Button-1>', show_folder_content)
folder_listbox.bind('<Double-1>', rename_folder)

filenames_listbox = tk.Listbox(listboxes_frame, width=60)
filenames_listbox.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

app.mainloop()


Can you explain this script to me using an example?