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

Add a button that creates renameable categories in the sidebar the categories are just…

  1. User

    Add a button that creates renameable categories in the sidebar the categories are just there to order the tables in to make it easier to navigate. Create them named "Untitled". The user should be able to drag tables in these categories to order them in the category. To visually distinguish categories and tables indent the tables by 5. Python 3.12 code: import tkinter as tk import tkinter.ttk as ttk from tkinter import simpledialog, messagebox, filedialog from tksheet import Sheet import json import csv from pathlib import Path import ctypes

    def set_dpi_awareness(): """Enable DPI awareness for high DPI settings.""" try: ctypes.windll.shcore.SetProcessDpiAwareness(1) except Exception as e: print(f"Error setting DPI awareness: {e}")

    class TableApp: def init(self, root): """Initialize the Table Editor application.""" self.root = root self.root.title("Table Editor with Sidebar") self.root.geometry("1280x720") self.config_fonts_and_colors() self.initialize_data() self.setup_ui() self.load_tables()

    def config_fonts_and_colors(self):
        """Configure fonts and colors."""
        font_name, font_size, font_style = "Literata", 12, "normal"
        self.default_font = (font_name, font_size, font_style)
        self.root.option_add("*Font", f"{font_name} {font_size}")
        self.TEXT_COLOR, self.BACKGROUND_COLOR = '#333333', '#FFFFFF'
        self.SIDEBAR_COLOR, self.BUTTON_COLOR = '#F7F8FC', '#F7F8FC'
        self.BUTTON_COLOR_SELECTED = '#EAEDEF'
    
    def setup_ui(self):
        """Set up the user interface components."""
        self.create_sidebar()
        self.create_main_frame()
        self.create_header_frame()
        self.create_table_frame()
    
    def create_sidebar(self):
        """Create the sidebar and its components."""
        sidebar = tk.Frame(self.root, width=200, bg=self.SIDEBAR_COLOR, bd=0, relief='flat')
        sidebar.pack(expand=False, fill='y', side='left', anchor='nw')
        tk.Frame(self.root, width=100, bg=self.BACKGROUND_COLOR, bd=0, relief='flat').pack(expand=False, fill='y', side='left', anchor='nw')
        
        # Create a frame for normal buttons
        normal_buttons_frame = tk.Frame(sidebar, bg=self.SIDEBAR_COLOR)
        normal_buttons_frame.pack(expand=False, fill='x', pady=10)
        
        # Create the "Create New Table" button
        create_table_label = self.create_clickable_label(normal_buttons_frame, "Create New Table", self.create_new_table)
        create_table_label.pack(padx=0, pady=10, fill='x')
        self.add_custom_hover(create_table_label)
    
        # Add a horizontal separator below the "Create New Table" button
        horiz_separator_create = ttk.Separator(normal_buttons_frame, orient='horizontal')
        horiz_separator_create.pack(fill='x', pady=5)
    
        self.table_labels_frame = tk.Frame(sidebar, bg=self.SIDEBAR_COLOR)
        self.table_labels_frame.pack(expand=True, fill='both', padx=0, pady=10)
    
        # Add a horizontal separator above the "Delete Selected Table" button
        horiz_separator_delete = ttk.Separator(sidebar, orient='horizontal')
        horiz_separator_delete.pack(expand=False, fill='x', pady=0)
    
        delete_table_label = self.create_clickable_label(
            sidebar, "Delete Selected Table", self.delete_table)
        delete_table_label.pack(padx=0, pady=10, fill='x', side='bottom')
        self.add_custom_hover(delete_table_label)
    
    def create_main_frame(self):
        """Create the main frame of the application."""
        self.main_frame = tk.Frame(self.root)
        self.main_frame.pack(expand=True, fill='both', side='right')
    
    def create_header_frame(self):
        """Create the header frame with filter and rename options."""
        header_frame = tk.Frame(self.main_frame, height=50, bg=self.BACKGROUND_COLOR)
        header_frame.pack(fill='x')
    
        tk.Label(header_frame, text="Filter:", bg=self.BACKGROUND_COLOR, fg=self.TEXT_COLOR).pack(side='left', padx=5, pady=10)
        self.filter_entry = tk.Entry(header_frame, fg=self.TEXT_COLOR)
        self.filter_entry.pack(side='left', padx=5, pady=10)
        self.filter_entry.bind("<KeyRelease>", lambda event: self.apply_filter())
    
        rename_headers = self.create_clickable_label(header_frame, "Rename Headers", self.rename_headers)
        rename_headers.pack(side='left', padx=5, pady=10, fill='x')
    
        import_table = self.create_clickable_label(header_frame, "Import Table", self.import_file)
        import_table.pack(side='right', padx=5, pady=10, fill='x')
    
        export_table = self.create_clickable_label(header_frame, "Export Table", self.export_table)
        export_table.pack(side='right', padx=5, pady=10, fill='x')
    
    def create_table_frame(self):
        """Create the frame to hold the table."""
        self.table_frame = tk.Frame(self.main_frame, bg=self.BACKGROUND_COLOR)
        self.table_frame.pack(expand=True, fill='both')
    
    def initialize_data(self):
        """Initialize data structures and variables."""
        self.save_file_dir = Path("tables")
        self.tables = {}
        self.table_labels = {}
        self.original_data = {}
        self.headers = {}
        self.current_table_name = None
        self.rename_entry = None
        self.selected_table_label = None
        self.save_file_dir.mkdir(exist_ok=True)
    
    def create_clickable_label(self, parent, text, command, allow_rename=True):
        """Create a clickable Label widget."""
        label = tk.Label(
            parent, text=text, bg=self.BUTTON_COLOR, fg=self.TEXT_COLOR,
            cursor='arrow', anchor='w', padx=10, pady=5
        )
        label.bind("<Button-1>", lambda e: command())
        if allow_rename:
            label.bind("<Double-1>", lambda e: self.begin_rename(text))
        return label
    
    def create_new_table(self):
        """Create a new table and add it to the available tables list."""
        table_name = f"Table {len(self.tables) + 1}"
        self.add_table(table_name)
        self.load_selected_table(table_name)
    
    def import_file(self):
        """Import a CSV or JSON file to create a new table."""
        file_path = filedialog.askopenfilename(
            title="Open File",
            filetypes=[("JSON files", "*.json"), ("CSV files", "*.csv")]
        )
        if not file_path:
            return
    
        try:
            if file_path.endswith('.csv'):
                with open(file_path, newline='', encoding='utf-8') as csvfile:
                    data = list(csv.reader(csvfile))
            elif file_path.endswith('.json'):
                with open(file_path, 'r', encoding='utf-8') as jsonfile:
                    data = json.load(jsonfile)
            else:
                raise ValueError("Unsupported file format.")
    
            headers, table_data = data[0], data[1:]
            self.add_table_from_data(file_path, headers, table_data)
    
        except Exception as e:
            messagebox.showerror("File Import Error", str(e))
    
    def add_table_from_data(self, file_path, headers, table_data):
        """Add a table with existing data."""
        table_name = Path(file_path).stem
        table_name = self.ensure_unique_table_name(table_name)
    
        self.add_table(table_name, table_data)
        self.headers[table_name] = headers
        self.load_selected_table(table_name)
        self.save_data(table_name)
    
    def ensure_unique_table_name(self, table_name):
        """Ensure that the table name is unique."""
        if table_name in self.tables:
            table_name += " (New)"
            while table_name in self.tables:
                table_name += " (New)"
        return table_name
    
    def export_table(self):
        """Prompt user to export the current table to CSV or JSON."""
        if not self.current_table_name:
            messagebox.showwarning("No Table Selected", "Please select a table to export.")
            return
    
        file_path = filedialog.asksaveasfilename(
            title="Save As",
            defaultextension=".json",
            filetypes=[("JSON files", "*.json"), ("CSV files", "*.csv")],
            initialfile=self.current_table_name
        )
    
        if not file_path:
            return
    
        try:
            data = [self.headers[self.current_table_name]] + self.tables[self.current_table_name].get_sheet_data()
            if file_path.endswith('.csv'):
                self.save_as_csv(file_path, data)
            elif file_path.endswith('.json'):
                self.save_as_json(file_path, data)
            else:
                raise ValueError("Unsupported file format.")
            
            messagebox.showinfo("Export Successful", f"Table '{self.current_table_name}' has been exported successfully.")
    
        except Exception as e:
            messagebox.showerror("Export Failed", f"An error occurred during export: {e}")
    
    def save_as_csv(self, file_path, data):
        """Save data as a CSV file."""
        with open(file_path, 'w', newline='', encoding='utf-8') as csvfile:
            csv.writer(csvfile).writerows(data)
    
    def save_as_json(self, file_path, data):
        """Save data as a JSON file."""
        with open(file_path, 'w', encoding='utf-8') as jsonfile:
            json.dump(data, jsonfile, indent=4)
    
    def add_table(self, table_name, data=None):
        """Add a table to the UI and internal storage."""
        default_data = [["" for _ in range(5)] for _ in range(10)]
        sheet = Sheet(
            self.table_frame,
            data=data or default_data,
            show_table=True,
            headers=None,
            font=self.default_font,
            header_font=self.default_font,
            auto_resize_columns=True
        )
        sheet.set_options(table_fg=self.TEXT_COLOR, header_fg=self.TEXT_COLOR)
        sheet.enable_bindings()
        sheet.extra_bindings([("end_edit_cell", lambda _, tn=table_name: self.save_data(tn))])
        sheet.pack_forget()
    
        self.tables[table_name] = sheet
        self.original_data[table_name] = sheet.get_sheet_data()
        self.headers.setdefault(table_name, sheet.headers())
    
        self.create_table_label(table_name)
    
    def create_table_label(self, table_name):
        """Create a clickable label for the table in the sidebar."""
        label = self.create_clickable_label(
            self.table_labels_frame, table_name,
            lambda name=table_name: self.load_selected_table(name)
        )
        label.pack(fill='x', pady=2)
        self.table_labels[table_name] = label
        self.add_custom_hover(label)
    
    def delete_table(self):
        """Delete the currently selected table."""
        if not self.current_table_name:
            messagebox.showwarning("No Table Selected", "Please select a table to delete.")
            return
    
        if messagebox.askyesno("Delete Table", f"Are you sure you want to delete the table '{self.current_table_name}'?"):
            self.remove_table(self.current_table_name)
    
    def remove_table(self, table_name):
        """Remove a table by its name."""
        self.tables[table_name].destroy()
        self.table_labels[table_name].destroy()
        del self.tables[table_name], self.original_data[table_name]
        del self.headers[table_name], self.table_labels[table_name]
        (self.save_file_dir / f"{table_name}.json").unlink(missing_ok=True)
        self.current_table_name, self.selected_table_label = None, None
    
    def load_tables(self):
        """Load existing tables from the directory."""
        for file_path in self.save_file_dir.glob("*.json"):
            table_name = file_path.stem
            with open(file_path, 'r') as file:
                data = json.load(file)
                
            headers, table_data = data.pop(0), data
            self.add_table(table_name, table_data)
            self.headers[table_name] = headers
    
    def load_selected_table(self, table_name):
        """Display the selected table and hide others."""
        for name, sheet in self.tables.items():
            is_selected = name == table_name
            sheet.pack(expand=is_selected, fill='both') if is_selected else sheet.pack_forget()
            if is_selected:
                self.current_table_name = table_name
                sheet.headers(self.headers[name])
                self.apply_filter()
                selected_label, self.selected_table_label = self.table_labels[name], self.table_labels[name]
                selected_label.config(bg=self.BUTTON_COLOR_SELECTED)
            else:
                self.table_labels[name].config(bg=self.BUTTON_COLOR)
        
    def save_data(self, table_name):
        """Save current data of a table to a file."""
        data = [self.headers[table_name]] + self.tables[table_name].get_sheet_data()
        file_path = self.save_file_dir / f"{table_name}.json"
        with file_path.open('w') as file:
            json.dump(data, file)
        print(f"Data for {table_name} saved successfully.")
    
    def apply_filter(self):
        """Apply filtering based on the entered term."""
        if not self.current_table_name:
            return
    
        term = self.filter_entry.get().lower()
        original_data = self.original_data[self.current_table_name]
        filtered_data = [row for row in original_data if any(term in str(cell).lower() for cell in row)]
        self.tables[self.current_table_name].set_sheet_data(filtered_data)
    
    def rename_headers(self):
        """Prompt user to rename headers of the currently selected table."""
        if not self.current_table_name:
            messagebox.showwarning("No Table Selected", "Please select a table to rename headers.")
            return
    
        current_headers = self.headers[self.current_table_name]
        new_headers = simpledialog.askstring(
            "Rename Headers",
            "Enter new headers (comma-separated):",
            initialvalue=", ".join(current_headers)
        )
    
        if new_headers:
            header_list = [header.strip() for header in new_headers.split(',')]
            self.headers[self.current_table_name] = header_list
            self.tables[self.current_table_name].headers(header_list)
            self.save_data(self.current_table_name)
    
    def begin_rename(self, table_name):
        """Begin renaming of the table with a double click."""
        if table_name not in self.table_labels:
            messagebox.showerror("Error", f"Table '{table_name}' not found.")
            return
    
        label = self.table_labels[table_name]
        if self.rename_entry:
            self.rename_entry.destroy()
    
        self.rename_entry = tk.Entry(self.table_labels_frame, bg=label.cget("bg"), fg=self.TEXT_COLOR, relief='flat')
        self.rename_entry.insert(0, table_name)
        self.rename_entry.place(x=label.winfo_x(), y=label.winfo_y(), width=label.winfo_width(), height=label.winfo_height())
        self.rename_entry.focus()
        self.rename_entry.select_range(0, tk.END)
        self.rename_entry.bind('<Return>', lambda _: self.end_rename(table_name))
        self.rename_entry.bind('<FocusOut>', lambda _: self.cancel_rename())
    
    def end_rename(self, old_name):
        """Finish the renaming process for the specified table."""
        new_name = self.rename_entry.get().strip()
    
        if not new_name:
            messagebox.showerror("Invalid Name", "Table name cannot be empty.")
            self.rename_entry.focus_set()
            return
    
        if new_name in self.tables and new_name != old_name:
            messagebox.showerror("Duplicate Name", f"A table named '{new_name}' already exists.")
            self.rename_entry.focus_set()
            return
    
        if new_name != old_name:
            self.update_table_name(old_name, new_name)
            self.load_selected_table(new_name)
    
        self.cancel_rename()
    
    def update_table_name(self, old_name, new_name):
        """Update table name and its associated resources."""
        if new_name not in self.tables:
            self.tables[new_name] = self.tables.pop(old_name)
            self.original_data[new_name] = self.original_data.pop(old_name)
            self.headers[new_name] = self.headers.pop(old_name)
    
            label = self.table_labels.pop(old_name)
            label.config(text=new_name)
            label.bind("<Button-1>", lambda e, tn=new_name: self.load_selected_table(tn))
            label.bind("<Double-1>", lambda e, tn=new_name: self.begin_rename(tn))  # Update to bind new name
    
            self.table_labels[new_name] = label
    
            if self.selected_table_label == label:
                self.selected_table_label.config(bg=self.BUTTON_COLOR_SELECTED)
    
            current_file = self.save_file_dir / f"{old_name}.json"
            new_file = self.save_file_dir / f"{new_name}.json"
            current_file.rename(new_file)
    
            self.load_selected_table(new_name)
    
    def cancel_rename(self):
        """Cancel the renaming entry."""
        if self.rename_entry:
            self.rename_entry.destroy()
            self.rename_entry = None
    
    def add_custom_hover(self, label):
        """Add custom hover effects to a label."""
        def on_enter(e):
            if label != self.selected_table_label:
                label.config(bg=self.BUTTON_COLOR_SELECTED)
    
        def on_leave(e):
            if label != self.selected_table_label:
                label.config(bg=self.BUTTON_COLOR)
    
        label.bind("<Enter>", on_enter)
        label.bind("<Leave>", on_leave)
    

    if name == "main": set_dpi_awareness() root = tk.Tk() app = TableApp(root) root.mainloop()

  2. Assistant

    To enhance your Tkinter application by adding renameable categories with drag-and-drop functionality in the sidebar, we'll modify your existing TableApp class. The categories will help organize tables, making navigation easier. Here's a comprehensive approach to achieve this:

    1. Use ttk.Treeview for Sidebar:

      • Replace the existing sidebar labels with a Treeview widget, allowing hierarchical organization (categories as parent nodes and tables as child nodes).
    2. Add Category Management:

      • Introduce a "Create Category" button to add new categories named "Untitled".
      • Enable renaming of both categories and tables via double-click.
    3. Implement Drag-and-Drop:

      • Allow users to drag tables from one category to another within the Treeview for reordering.
    4. Visual Indentation:

      • The Treeview inherently handles indentation, distinguishing categories from tables.

    Below is the updated Python 3.12 code incorporating these features:

    import tkinter as tk
    import tkinter.ttk as ttk
    from tkinter import simpledialog, messagebox, filedialog
    from tksheet import Sheet
    import json
    import csv
    from pathlib import Path
    import ctypes
    
    def set_dpi_awareness():
        """Enable DPI awareness for high DPI settings."""
        try:
            ctypes.windll.shcore.SetProcessDpiAwareness(1)
        except Exception as e:
            print(f"Error setting DPI awareness: {e}")
    
    class TableApp:
        def __init__(self, root):
            """Initialize the Table Editor application."""
            self.root = root
            self.root.title("Table Editor with Sidebar")
            self.root.geometry("1280x720")
            self.config_fonts_and_colors()
            self.initialize_data()
            self.setup_ui()
            self.load_tables()
    
        def config_fonts_and_colors(self):
            """Configure fonts and colors."""
            font_name, font_size, font_style = "Literata", 12, "normal"
            self.default_font = (font_name, font_size, font_style)
            self.root.option_add("*Font", f"{font_name} {font_size}")
            self.TEXT_COLOR, self.BACKGROUND_COLOR = '#333333', '#FFFFFF'
            self.SIDEBAR_COLOR, self.BUTTON_COLOR = '#F7F8FC', '#F7F8FC'
            self.BUTTON_COLOR_SELECTED = '#EAEDEF'
    
        def setup_ui(self):
            """Set up the user interface components."""
            self.create_sidebar()
            self.create_main_frame()
            self.create_header_frame()
            self.create_table_frame()
    
        def create_sidebar(self):
            """Create the sidebar and its components."""
            sidebar = tk.Frame(self.root, width=200, bg=self.SIDEBAR_COLOR, bd=0, relief='flat')
            sidebar.pack(expand=False, fill='y', side='left', anchor='nw')
            tk.Frame(self.root, width=100, bg=self.BACKGROUND_COLOR, bd=0, relief='flat').pack(expand=False, fill='y', side='left', anchor='nw')
            
            # Create a frame for sidebar buttons
            sidebar_buttons_frame = tk.Frame(sidebar, bg=self.SIDEBAR_COLOR)
            sidebar_buttons_frame.pack(expand=False, fill='x', pady=10)
            
            # "Create New Table" Button
            create_table_label = self.create_clickable_label(sidebar_buttons_frame, "Create New Table", self.create_new_table)
            create_table_label.pack(padx=0, pady=5, fill='x')
            self.add_custom_hover(create_table_label)
            
            # "Create New Category" Button
            create_category_label = self.create_clickable_label(sidebar_buttons_frame, "Create New Category", self.create_new_category)
            create_category_label.pack(padx=0, pady=5, fill='x')
            self.add_custom_hover(create_category_label)
            
            # Separator
            ttk.Separator(sidebar_buttons_frame, orient='horizontal').pack(fill='x', pady=5)
            
            # Treeview for Categories and Tables
            self.tree = ttk.Treeview(sidebar, selectmode='browse')
            self.tree.pack(expand=True, fill='both', padx=5, pady=5)
            self.tree.bind("<Double-1>", self.on_treeview_double_click)
            self.tree.bind("<ButtonPress-1>", self.on_treeview_button_press)
            self.tree.bind("<B1-Motion>", self.on_treeview_mouse_motion)
            self.tree.bind("<ButtonRelease-1>", self.on_treeview_button_release)
            
            # Define tags for styling
            self.tree.tag_configure('category', font=self.default_font, foreground=self.TEXT_COLOR)
            self.tree.tag_configure('table', font=self.default_font, foreground=self.TEXT_COLOR, padding=(20, 0, 0, 0))
            
            # Initialize drag-and-drop variables
            self.dragging_item = None
    
            # "Delete Selected Item" Button
            delete_item_label = self.create_clickable_label(
                sidebar, "Delete Selected Item", self.delete_selected_item)
            delete_item_label.pack(padx=0, pady=5, fill='x', side='bottom')
            self.add_custom_hover(delete_item_label)
    
        def create_main_frame(self):
            """Create the main frame of the application."""
            self.main_frame = tk.Frame(self.root)
            self.main_frame.pack(expand=True, fill='both', side='right')
    
        def create_header_frame(self):
            """Create the header frame with filter and rename options."""
            header_frame = tk.Frame(self.main_frame, height=50, bg=self.BACKGROUND_COLOR)
            header_frame.pack(fill='x')
        
            tk.Label(header_frame, text="Filter:", bg=self.BACKGROUND_COLOR, fg=self.TEXT_COLOR).pack(side='left', padx=5, pady=10)
            self.filter_entry = tk.Entry(header_frame, fg=self.TEXT_COLOR)
            self.filter_entry.pack(side='left', padx=5, pady=10)
            self.filter_entry.bind("<KeyRelease>", lambda event: self.apply_filter())
        
            rename_headers = self.create_clickable_label(header_frame, "Rename Headers", self.rename_headers)
            rename_headers.pack(side='left', padx=5, pady=10, fill='x')
        
            import_table = self.create_clickable_label(header_frame, "Import Table", self.import_file)
            import_table.pack(side='right', padx=5, pady=10, fill='x')
        
            export_table = self.create_clickable_label(header_frame, "Export Table", self.export_table)
            export_table.pack(side='right', padx=5, pady=10, fill='x')
    
        def create_table_frame(self):
            """Create the frame to hold the table."""
            self.table_frame = tk.Frame(self.main_frame, bg=self.BACKGROUND_COLOR)
            self.table_frame.pack(expand=True, fill='both')
    
        def initialize_data(self):
            """Initialize data structures and variables."""
            self.save_file_dir = Path("tables")
            self.tables = {}
            self.original_data = {}
            self.headers = {}
            self.current_table_name = None
            self.rename_entry = None
            self.selected_item = None
            self.save_file_dir.mkdir(exist_ok=True)
            self.categories = {}  # category_name: list of table_names
    
        def create_clickable_label(self, parent, text, command):
            """Create a clickable Label widget."""
            label = tk.Label(
                parent, text=text, bg=self.BUTTON_COLOR, fg=self.TEXT_COLOR,
                cursor='arrow', anchor='w', padx=10, pady=5
            )
            label.bind("<Button-1>", lambda e: command())
            label.bind("<Double-1>", lambda e: None)  # Override double-click if necessary
            return label
    
        def create_new_table(self):
            """Create a new table and add it to the available tables list."""
            table_name = f"Table {len(self.tables) + 1}"
            self.add_table(table_name)
            self.add_table_to_category(table_name, self.get_default_category())
            self.load_selected_table(table_name)
    
        def create_new_category(self):
            """Create a new category named 'Untitled'."""
            category_name = "Untitled"
            counter = 1
            unique_name = category_name
            while unique_name in self.categories:
                unique_name = f"{category_name} ({counter})"
                counter += 1
            self.categories[unique_name] = []
            self.tree.insert('', 'end', iid=unique_name, text=unique_name, tags=('category',))
            self.tree.item(unique_name, open=True)  # Expand the category
            self.save_categories()
    
        def get_default_category(self):
            """Return the first category or create one if none exist."""
            if not self.categories:
                self.create_new_category()
            return list(self.categories.keys())[0]
    
        def add_table_to_category(self, table_name, category_name):
            """Associate a table with a category."""
            if category_name not in self.categories:
                self.categories[category_name] = []
            self.categories[category_name].append(table_name)
            self.tree.insert(category_name, 'end', iid=table_name, text=table_name, tags=('table',))
            self.save_categories()
    
        def add_table(self, table_name, data=None):
            """Add a table to the UI and internal storage."""
                default_data = [["" for _ in range(5)] for _ in range(10)]
                sheet = Sheet(
                    self.table_frame,
                    data=data or default_data,
                    show_table=True,
                    headers=None,
                    font=self.default_font,
                    header_font=self.default_font,
                    auto_resize_columns=True
                )
                sheet.set_options(table_fg=self.TEXT_COLOR, header_fg=self.TEXT_COLOR)
                sheet.enable_bindings()
                sheet.extra_bindings([("end_edit_cell", lambda _, tn=table_name: self.save_data(tn))])
                sheet.pack_forget()
        
                self.tables[table_name] = sheet
                self.original_data[table_name] = sheet.get_sheet_data()
                self.headers.setdefault(table_name, sheet.headers())
        
        def delete_selected_item(self):
            """Delete the selected category or table."""
            selected = self.tree.selection()
            if not selected:
                messagebox.showwarning("No Selection", "Please select a category or table to delete.")
                return
            item = selected[0]
            if 'category' in self.tree.item(item, "tags"):
                if messagebox.askyesno("Delete Category", f"Are you sure you want to delete the category '{item}'? All tables within will be moved to the default category."):
                    self.move_tables_to_default(item)
                    self.tree.delete(item)
                    del self.categories[item]
            elif 'table' in self.tree.item(item, "tags"):
                if messagebox.askyesno("Delete Table", f"Are you sure you want to delete the table '{item}'?"):
                    self.remove_table(item)
            self.save_categories()
    
        def move_tables_to_default(self, category_name):
            """Move all tables from a deleted category to the default category."""
            default_category = self.get_default_category()
            tables = self.categories.get(category_name, [])
            for table in tables:
                self.categories[default_category].append(table)
                self.tree.move(table, default_category, 'end')
            self.categories[category_name] = []
    
        def on_treeview_double_click(self, event):
            """Handle double-click for renaming."""
            item = self.tree.identify_row(event.y)
            if item:
                self.begin_rename(item)
    
        def begin_rename(self, item):
            """Begin renaming of the selected item."""
            if 'category' in self.tree.item(item, "tags") or 'table' in self.tree.item(item, "tags"):
                x, y, width, height = self.tree.bbox(item)
                value = self.tree.item(item, "text")
                self.rename_entry = tk.Entry(self.tree, font=self.default_font)
                self.rename_entry.insert(0, value)
                self.rename_entry.place(x=x, y=y, width=width, height=height)
                self.rename_entry.focus()
                self.rename_entry.bind('<Return>', lambda e: self.end_rename(item))
                self.rename_entry.bind('<FocusOut>', lambda e: self.cancel_rename())
    
        def end_rename(self, item):
            """Finish renaming the specified item."""
            new_name = self.rename_entry.get().strip()
            if not new_name:
                messagebox.showerror("Invalid Name", "Name cannot be empty.")
                self.rename_entry.focus_set()
                return
            # Check for duplicates
            if new_name in self.categories or new_name in self.tables:
                messagebox.showerror("Duplicate Name", f"An item named '{new_name}' already exists.")
                self.rename_entry.focus_set()
                return
            old_name = self.tree.item(item, "text")
            self.tree.item(item, text=new_name)
            if 'category' in self.tree.item(item, "tags"):
                self.categories[new_name] = self.categories.pop(old_name)
                # Update parent-child relationships if necessary
                for table in self.categories[new_name]:
                    self.tree.item(table, open=True)
            elif 'table' in self.tree.item(item, "tags"):
                # Update tables dictionary
                self.tables[new_name] = self.tables.pop(old_name)
                self.original_data[new_name] = self.original_data.pop(old_name)
                self.headers[new_name] = self.headers.pop(old_name)
                # Update file
                current_file = self.save_file_dir / f"{old_name}.json"
                new_file = self.save_file_dir / f"{new_name}.json"
                if current_file.exists():
                    current_file.rename(new_file)
            self.rename_entry.destroy()
            self.rename_entry = None
            self.save_categories()
    
        def cancel_rename(self):
            """Cancel the renaming entry."""
            if self.rename_entry:
                self.rename_entry.destroy()
                self.rename_entry = None
    
        def on_treeview_button_press(self, event):
            """Handle the start of a drag."""
            item = self.tree.identify_row(event.y)
            if item and 'table' in self.tree.item(item, "tags"):
                self.dragging_item = item
    
        def on_treeview_mouse_motion(self, event):
            """Handle the dragging motion."""
            if self.dragging_item:
                self.tree.config(cursor="hand2")
    
        def on_treeview_button_release(self, event):
            """Handle the drop."""
            if self.dragging_item:
                self.tree.config(cursor="")
                target_item = self.tree.identify_row(event.y)
                if target_item and 'category' in self.tree.item(target_item, "tags"):
                    self.tree.move(self.dragging_item, target_item, 'end')
                    # Update internal category list
                    for category, tables in self.categories.items():
                        if self.dragging_item in tables:
                            tables.remove(self.dragging_item)
                            break
                    self.categories[target_item].append(self.dragging_item)
                    self.save_categories()
                self.dragging_item = None
    
        def load_tables(self):
            """Load existing tables from the directory."""
            for file_path in self.save_file_dir.glob("*.json"):
                table_name = file_path.stem
                with open(file_path, 'r') as file:
                    data = json.load(file)
                    
                headers, table_data = data.pop(0), data
                self.add_table(table_name, table_data)
                self.headers[table_name] = headers
                self.original_data[table_name] = table_data
            self.update_treeview()
    
        def update_treeview(self):
            """Populate the Treeview with categories and tables."""
            # Clear existing items
            for item in self.tree.get_children():
                self.tree.delete(item)
            # Re-populate
            for category, tables in self.categories.items():
                self.tree.insert('', 'end', iid=category, text=category, tags=('category',))
                self.tree.item(category, open=True)
                for table in tables:
                    if table in self.tables:
                        self.tree.insert(category, 'end', iid=table, text=table, tags=('table',))
    
        def load_selected_table(self, table_name):
            """Display the selected table and hide others."""
            if self.current_table_name:
                self.tables[self.current_table_name].pack_forget()
                # Reset previous selection's background
            for name, sheet in self.tables.items():
                if name == table_name:
                    sheet.pack(expand=True, fill='both')
                    self.current_table_name = table_name
                    sheet.headers(self.headers[name])
                    self.apply_filter()
                    self.highlight_treeview_item(table_name)
                else:
                    sheet.pack_forget()
    
        def highlight_treeview_item(self, table_name):
            """Highlight the selected table in the Treeview."""
            # Deselect all
            self.tree.selection_remove(*self.tree.selection())
            # Select the current table
            if table_name in self.tree.get_children():
                # It's a category
                self.tree.selection_set(table_name)
                self.tree.see(table_name)
            else:
                # It's a table
                self.tree.selection_set(table_name)
                self.tree.see(table_name)
    
        def save_data(self, table_name):
            """Save current data of a table to a file."""
            data = [self.headers[table_name]] + self.tables[table_name].get_sheet_data()
            file_path = self.save_file_dir / f"{table_name}.json"
            with file_path.open('w') as file:
                json.dump(data, file)
            print(f"Data for {table_name} saved successfully.")
    
        def apply_filter(self):
            """Apply filtering based on the entered term."""
            if not self.current_table_name:
                return
    
            term = self.filter_entry.get().lower()
            original_data = self.original_data[self.current_table_name]
            if term:
                filtered_data = [row for row in original_data if any(term in str(cell).lower() for cell in row)]
            else:
                filtered_data = original_data
            self.tables[self.current_table_name].set_sheet_data(filtered_data)
    
        def rename_headers(self):
            """Prompt user to rename headers of the currently selected table."""
            if not self.current_table_name:
                messagebox.showwarning("No Table Selected", "Please select a table to rename headers.")
                return
    
            current_headers = self.headers[self.current_table_name]
            new_headers = simpledialog.askstring(
                "Rename Headers",
                "Enter new headers (comma-separated):",
                initialvalue=", ".join(current_headers)
            )
    
            if new_headers:
                header_list = [header.strip() for header in new_headers.split(',')]
                self.headers[self.current_table_name] = header_list
                self.tables[self.current_table_name].headers(header_list)
                self.save_data(self.current_table_name)
    
        def import_file(self):
            """Import a CSV or JSON file to create a new table."""
            file_path = filedialog.askopenfilename(
                title="Open File",
                filetypes=[("JSON files", "*.json"), ("CSV files", "*.csv")]
            )
            if not file_path:
                return
    
            try:
                if file_path.endswith('.csv'):
                    with open(file_path, newline='', encoding='utf-8') as csvfile:
                        data = list(csv.reader(csvfile))
                elif file_path.endswith('.json'):
                    with open(file_path, 'r', encoding='utf-8') as jsonfile:
                        data = json.load(jsonfile)
                else:
                    raise ValueError("Unsupported file format.")
    
                headers, table_data = data[0], data[1:]
                self.add_table_from_data(file_path, headers, table_data)
    
            except Exception as e:
                messagebox.showerror("File Import Error", str(e))
    
        def add_table_from_data(self, file_path, headers, table_data):
            """Add a table with existing data."""
            table_name = Path(file_path).stem
            table_name = self.ensure_unique_table_name(table_name)
    
            self.add_table(table_name, table_data)
            self.headers[table_name] = headers
            self.original_data[table_name] = table_data
            self.add_table_to_category(table_name, self.get_default_category())
            self.load_selected_table(table_name)
            self.save_data(table_name)
            self.update_treeview()
    
        def ensure_unique_table_name(self, table_name):
            """Ensure that the table name is unique."""
            if table_name in self.tables:
                table_name += " (New)"
                while table_name in self.tables:
                    table_name += " (New)"
            return table_name
    
        def export_table(self):
            """Prompt user to export the current table to CSV or JSON."""
            if not self.current_table_name:
                messagebox.showwarning("No Table Selected", "Please select a table to export.")
                return
    
            file_path = filedialog.asksaveasfilename(
                title="Save As",
                defaultextension=".json",
                filetypes=[("JSON files", "*.json"), ("CSV files", "*.csv")],
                initialfile=self.current_table_name
            )
    
            if not file_path:
                return
    
            try:
                data = [self.headers[self.current_table_name]] + self.tables[self.current_table_name].get_sheet_data()
                if file_path.endswith('.csv'):
                    self.save_as_csv(file_path, data)
                elif file_path.endswith('.json'):
                    self.save_as_json(file_path, data)
                else:
                    raise ValueError("Unsupported file format.")
                
                messagebox.showinfo("Export Successful", f"Table '{self.current_table_name}' has been exported successfully.")
    
            except Exception as e:
                messagebox.showerror("Export Failed", f"An error occurred during export: {e}")
    
        def save_as_csv(self, file_path, data):
            """Save data as a CSV file."""
            with open(file_path, 'w', newline='', encoding='utf-8') as csvfile:
                csv.writer(csvfile).writerows(data)
    
        def save_as_json(self, file_path, data):
            """Save data as a JSON file."""
            with open(file_path, 'w', encoding='utf-8') as jsonfile:
                json.dump(data, jsonfile, indent=4)
    
        def remove_table(self, table_name):
            """Remove a table by its name."""
            # Remove from UI
            if table_name in self.tables:
                self.tables[table_name].destroy()
                del self.tables[table_name]
            # Remove from Treeview
            if table_name in self.tree.get_children():
                self.tree.delete(table_name)
            # Remove from internal structures
            if table_name in self.original_data:
                del self.original_data[table_name]
            if table_name in self.headers:
                del self.headers[table_name]
            # Remove the file
            (self.save_file_dir / f"{table_name}.json").unlink(missing_ok=True)
            # Remove from categories
            for tables in self.categories.values():
                if table_name in tables:
                    tables.remove(table_name)
            self.current_table_name = None
    
        def save_categories(self):
            """Save the current category structure to a file."""
            categories_file = self.save_file_dir / "categories.json"
            with categories_file.open('w') as file:
                json.dump(self.categories, file, indent=4)
    
        def load_categories(self):
            """Load categories from a file."""
            categories_file = self.save_file_dir / "categories.json"
            if categories_file.exists():
                with categories_file.open('r') as file:
                    self.categories = json.load(file)
            else:
                self.categories = {}
                self.save_categories()
    
        def save_all_data(self):
            """Save all tables and categories."""
            for table_name in self.tables:
                self.save_data(table_name)
            self.save_categories()
    
        def on_close(self):
            """Handle application closing."""
            self.save_all_data()
            self.root.destroy()
    
        def run(self):
            """Run the application."""
            self.root.protocol("WM_DELETE_WINDOW", self.on_close)
            self.root.mainloop()
    
        def add_custom_hover(self, label):
            """Add custom hover effects to a label."""
            def on_enter(e):
                label.config(bg=self.BUTTON_COLOR_SELECTED)
    
            def on_leave(e):
                label.config(bg=self.BUTTON_COLOR)
    
            label.bind("<Enter>", on_enter)
            label.bind("<Leave>", on_leave)
    
    if __name__ == "__main__":
        set_dpi_awareness()
        root = tk.Tk()
        app = TableApp(root)
        app.load_categories()
        app.run()
    

    Explanation of the Changes:

    1. Sidebar Enhancements:

      • Treeview Widget: Replaced the self.table_labels_frame with a ttk.Treeview named self.tree. This widget allows hierarchical representation of categories and tables.
      • Category and Table Tags: Defined 'category' and 'table' tags for styling purposes.
      • Create Category Button: Added a "Create New Category" button to allow users to create new categories with the default name "Untitled". If "Untitled" already exists, it appends a number to make it unique.
    2. Category Management:

      • Categories Dictionary: Introduced self.categories to keep track of categories and their associated tables.
      • Adding Tables to Categories: When a new table is created or imported, it's automatically added to the default category.
      • Deleting Items: The "Delete Selected Item" button now handles deletion of both categories and tables. Deleting a category moves its tables to the default category.
    3. Renaming Functionality:

      • Double-Click to Rename: Users can double-click on either a category or table to rename it. An Entry widget overlays the item for renaming.
      • Validation: Ensures that the new name is not empty and doesn't duplicate existing category or table names.
    4. Drag-and-Drop Functionality:

      • Drag Start: On mouse button press, if a table is selected, it begins the drag operation.
      • Dragging Motion: Changes the cursor to indicate dragging.
      • Drop Handling: On mouse release, if the drop target is a category, the table is moved to that category both in the UI and the internal self.categories dictionary.
    5. Data Persistence:

      • Categories Saving: Categories and their associated tables are saved to categories.json within the tables directory.
      • Loading Categories: On startup, the application loads existing categories and reconstructs the Treeview accordingly.
    6. Visual Indentation:

      • Treeview Indentation: The ttk.Treeview inherently indents child items (tables) under parent items (categories), providing a clear visual distinction.
    7. Other Enhancements:

      • Highlighting Selected Table: When a table is selected, it's highlighted in the Treeview.
      • Error Handling: Added necessary error messages for invalid operations.

    Additional Notes:

    • Dependencies: Ensure that you have the tksheet library installed. You can install it using pip:

      pip install tksheet
      
    • File Structure: The application saves tables as JSON files within the tables directory. Categories are saved in a categories.json file within the same directory.

    • Default Category: If no category exists, a default category is created automatically when adding a new table.

    • Drag-and-Drop Limitations: The current implementation allows moving tables between categories but does not support reordering tables within a category. Enhancements can be made to support full drag-and-drop reordering if needed.

    This comprehensive update should provide you with a more organized and user-friendly interface for managing tables within categorized sections, enhancing navigation and usability.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.