Recommedn ways to split this class into several classes to increase readebility: class…
- User
Recommedn ways to split this class into several classes to increase readebility: class TableManager: """Deals with table operations like creation, deletion, loading, and saving."""
def __init__(self, app: TableApp): self.app = app def create_new_table(self): """Create a new table.""" existing_numbers = [ int(name.split(" ")[1]) for name in self.app.data_manager.tables_data if name.startswith("Table ") and name.split(" ")[1].isdigit() ] next_number = max(existing_numbers, default=0) + 1 table_name = f"Table {next_number}" self.add_table(table_name) self.load_selected_table(table_name) def add_table( self, table_name: str, data: list[list[str]] | None = None, headers: Optional[list[str]] = None, ): """Add a new table.""" if headers: self.app.data_manager.headers[table_name] = headers else: default_headers = [ "Column 1", "Column 2", "Column 3", "Column 4", "Column 5", ] self.app.data_manager.headers[table_name] = default_headers self.app.data_manager.tables_data[table_name] = { "headers": self.app.data_manager.headers[table_name], "data": data or [ ["" for _ in range(len(self.app.data_manager.headers[table_name]))] for _ in range(10) ], } self.app.sidebar.create_table_label(table_name) self.app.data_manager.save_data() def load_selected_table(self, table_name: str): """Display selected table.""" if self.app.current_sheet: self.app.current_sheet.pack_forget() self.app.current_sheet.destroy() self.app.current_sheet = None if self.app.sidebar.selected_table_label: try: self.app.sidebar.selected_table_label.config( bg=self.app.colors["button"] ) except tk.TclError: self.app.sidebar.selected_table_label = None if table_name not in self.app.data_manager.tables_data: messagebox.showerror("Error", f"Table '{table_name}' does not exist.") self.app.current_table_name = None self.app.sidebar.selected_table_label = None return table_info = self.app.data_manager.tables_data[table_name] headers = table_info["headers"] data = table_info["data"] try: sheet = Sheet( self.app.table_frame, data=data, show_table=True, headers=headers, font=self.app.fonts["tksheet"], header_font=self.app.fonts["tksheet"], auto_resize_columns=True, ) sheet.set_options( table_fg=self.app.colors["text"], header_fg=self.app.colors["text"] ) sheet.enable_bindings() sheet.extra_bindings( [ ("end_edit_cell", self.on_cell_edit), ("end_delete_columns", self.on_columns_deleted), ] ) sheet.pack(expand=True, fill="both") self.app.current_sheet = sheet self.app.current_table_name = table_name if self.app.header.table_name_label: self.app.header.table_name_label.config(text=self.app.current_table_name) else: self.app.header.table_name_label = tk.Label( self.app.root, text=self.app.current_table_name, bg=self.app.colors["background"], fg=self.app.colors["text"], font=self.app.fonts["header_info"], ) self.app.header.table_name_label.grid( row=0, column=0, padx=(60, 10), pady=(5, 0), sticky="nw" ) label = self.app.sidebar.table_labels.get(table_name) if label: self.app.sidebar.selected_table_label = label try: self.app.sidebar.selected_table_label.config( bg=self.app.colors["button_selected"] ) except tk.TclError: self.app.sidebar.selected_table_label = None messagebox.showerror( "Error", f"Failed to update the label for '{table_name}'." ) else: self.app.sidebar.selected_table_label = None messagebox.showerror("Error", f"Label for '{table_name}' not found.") self.app.filter_controls.filter_header_var.set("All") self.app.filter_controls.filter_header_dropdown["values"] = ["All"] + headers self.app.filter_controls.filter_option_var.set("contains") self.app.filter_controls.update_filter_text_state() self.app.apply_filter() except Exception as e: messagebox.showerror( "Sheet Error", f"Failed to load table '{table_name}': {e}" ) self.app.current_table_name = None self.app.sidebar.selected_table_label = None def on_cell_edit(self, event=None): """Handle cell edits.""" if self.app.current_table_name and self.app.current_sheet: sheet_data = self.app.current_sheet.get_sheet_data() for idx, row in enumerate(sheet_data): if idx < len(self.app.displayed_row_indices): data_idx = self.app.displayed_row_indices[idx] self.app.data_manager.tables_data[self.app.current_table_name][ "data" ][data_idx] = row else: # Handle new rows by appending to the underlying data self.app.data_manager.tables_data[self.app.current_table_name][ "data" ].append(row) self.app.data_manager.save_data() def on_columns_deleted(self, event): """Handle column deletion and update filter headers.""" if not self.app.current_table_name or not self.app.current_sheet: return new_headers = self.app.current_sheet.headers() self.app.data_manager.headers[self.app.current_table_name] = new_headers self.app.filter_controls.filter_header_dropdown["values"] = ["All"] + new_headers self.app.filter_controls.filter_header_var.set("All") self.app.filter_controls.filter_option_var.set("contains") self.app.filter_controls.filter_text_var.set("") self.app.filter_controls.filter_text_entry.config(state="normal") self.app.apply_filter() def import_file(self): """Import table from file.""" file_path = filedialog.askopenfilename( title="Import File", filetypes=[ ("All Supported Files", "*.json *.csv"), ("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.") if ( not data or not isinstance(data, list) or not all(isinstance(row, list) for row in data) ): raise ValueError("Invalid data format in the file.") 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: str, headers: list[str], table_data: list[list[str]] ): """Add a table from file data.""" table_name = Path(file_path).stem table_name = self.ensure_unique_table_name(table_name) self.add_table(table_name, data=table_data, headers=headers) self.load_selected_table(table_name) self.app.data_manager.save_data() def ensure_unique_table_name(self, table_name: str) -> str: """Ensure table name is unique.""" original_name = table_name counter = 1 while table_name in self.app.data_manager.tables_data: table_name = f"{original_name} (New {counter})" counter += 1 return table_name def export_table(self): """Export current table to file.""" if ( not self.app.current_table_name or self.app.current_table_name not in self.app.data_manager.tables_data ): messagebox.showwarning( "No Table Selected", "Please select a table to export." ) return file_path = filedialog.asksaveasfilename( title="Export File", defaultextension=".json", filetypes=[("JSON files", "*.json"), ("CSV files", "*.csv")], initialfile=self.app.current_table_name, ) if not file_path: return try: data = [ self.app.data_manager.headers[self.app.current_table_name] ] + self.app.data_manager.tables_data[self.app.current_table_name]["data"] if file_path.endswith(".csv"): self.save_table_data(file_path, data, "csv") elif file_path.endswith(".json"): with open(file_path, "w", encoding="utf-8") as file: json.dump(data, file, indent=4) else: raise ValueError("Unsupported file format.") self.app.data_manager.save_data() messagebox.showinfo( "Export Successful", f"Table '{self.app.current_table_name}' has been exported successfully.", ) except Exception as e: messagebox.showerror( "Export Failed", f"An error occurred during export: {e}" ) def save_table_data(self, file_path: str, data: list[list[str]], format: str): """Save table data in specified format.""" match format: case "csv": with open(file_path, "w", newline="", encoding="utf-8") as file: csv.writer(file).writerows(data) case "json": with open(file_path, "w", encoding="utf-8") as file: json.dump(data, file, indent=4) case _: raise ValueError("Unsupported file format.") def delete_table(self): """Delete selected table.""" if ( not self.app.current_table_name or self.app.current_table_name not in self.app.data_manager.tables_data ): messagebox.showwarning( "No Table Selected", "Please select a valid table to delete." ) return if messagebox.askyesno( "Delete Table", f"Are you sure you want to delete the table '{self.app.current_table_name}'?", ): self.remove_table(self.app.current_table_name) def remove_table(self, table_name: str): """Remove a table.""" if self.app.current_table_name == table_name and self.app.current_sheet: self.app.current_sheet.destroy() self.app.current_sheet = None label = self.app.sidebar.table_labels.get(table_name) if label: label.destroy() if table_name in self.app.data_manager.tables_data: del self.app.data_manager.tables_data[table_name] if table_name in self.app.data_manager.headers: del self.app.data_manager.headers[table_name] if table_name in self.app.sidebar.table_labels: del self.app.sidebar.table_labels[table_name] self.app.current_table_name = None self.app.sidebar.selected_table_label = None self.app.data_manager.save_data() self.app.sidebar.sort_table_labels() def rename_headers(self): """Rename table headers.""" if not self.app.current_table_name: messagebox.showwarning( "No Table Selected", "Please select a table to rename headers." ) return current_headers = self.app.data_manager.headers[self.app.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(",")] if not header_list: messagebox.showerror("Invalid Headers", "Header list cannot be empty.") return self.app.data_manager.headers[self.app.current_table_name] = header_list self.app.data_manager.tables_data[self.app.current_table_name][ "headers" ] = header_list if self.app.current_sheet: try: self.app.current_sheet.headers(header_list) except tk.TclError as e: messagebox.showerror("Error", f"Failed to rename headers: {e}") self.app.filter_controls.filter_header_var.set("All") self.app.filter_controls.filter_header_dropdown["values"] = [ "All" ] + header_list self.app.apply_filter() self.app.data_manager.save_data() def begin_rename(self, table_name: str): """Start renaming a table.""" if table_name not in self.app.sidebar.table_labels: messagebox.showerror("Error", f"Table '{table_name}' not found.") return label = self.app.sidebar.table_labels[table_name] self.cancel_rename() self.app.sidebar.rename_entry = tk.Entry( self.app.sidebar.table_labels_frame, bg=label.cget("bg"), fg=self.app.colors["text"], relief="flat", ) self.app.sidebar.rename_entry.insert(0, table_name) self.app.sidebar.rename_entry.place( x=label.winfo_x(), y=label.winfo_y(), width=label.winfo_width(), height=label.winfo_height(), ) self.app.sidebar.rename_entry.focus() self.app.sidebar.rename_entry.select_range(0, tk.END) self.app.sidebar.rename_entry.bind( "<Return>", lambda event: self.end_rename(table_name) ) self.app.sidebar.rename_entry.bind("<FocusOut>", lambda event: self.cancel_rename()) def end_rename(self, old_name: str): """Finalize table renaming.""" new_name = self.app.sidebar.rename_entry.get().strip() if not new_name: messagebox.showerror("Invalid Name", "Table name cannot be empty.") self.app.sidebar.rename_entry.focus_set() return if new_name in self.app.data_manager.tables_data and new_name != old_name: messagebox.showerror( "Duplicate Name", f"A table named '{new_name}' already exists." ) self.app.sidebar.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: str, new_name: str): """Update table name and resources.""" self.app.data_manager.tables_data[new_name] = self.app.data_manager.tables_data.pop( old_name ) self.app.data_manager.headers[new_name] = self.app.data_manager.headers.pop( old_name ) label = self.app.sidebar.table_labels.pop(old_name) label.config(text=new_name) label.bind( "<Button-1>", lambda event: self.load_selected_table(new_name) ) label.bind( "<Double-1>", lambda event: self.begin_rename(new_name) ) self.app.sidebar.table_labels[new_name] = label if self.app.sidebar.selected_table_label == label: try: label.config(bg=self.app.colors["button_selected"]) except tk.TclError: pass self.app.data_manager.save_data() self.app.sidebar.sort_table_labels() def cancel_rename(self): """Cancel rename operation.""" if self.app.sidebar.rename_entry: self.app.sidebar.rename_entry.destroy() self.app.sidebar.rename_entry = None - Assistant
To improve the readability and maintainability of the
TableManagerclass and reduce its size, you can split it into several smaller classes based on the different responsibilities and functionalities it handles. Here's a possible structure to consider:1. TableCreationManager
Handles table creation and adding new tables.
class TableCreationManager: """Handles creation and addition of new tables.""" def __init__(self, app: TableApp): self.app = app def create_new_table(self): # Existing logic for creating a new table pass def add_table(self, table_name: str, data: list[list[str]] = None, headers: Optional[list[str]] = None): # Logic for adding a new table pass def ensure_unique_table_name(self, table_name: str) -> str: # Logic for ensuring unique table names pass2. TableLoadingManager
Handles table loading and interactions like edits and deletions.
class TableLoadingManager: """Handles loading, editing and deleting operations on tables.""" def __init__(self, app: TableApp): self.app = app def load_selected_table(self, table_name: str): # Logic for loading a selected table pass def on_cell_edit(self, event=None): # Logic for handling cell edits pass def on_columns_deleted(self, event): # Logic for handling column deletions pass def delete_table(self): # Logic for deleting a table pass def remove_table(self, table_name: str): # Logic for removing a table pass3. TableFileManager
Handles import and export operations for tables.
class TableFileManager: """Handles import and export operations for table data.""" def __init__(self, app: TableApp): self.app = app def import_file(self): # Logic for importing tables from a file pass def export_table(self): # Logic for exporting tables to a file pass def save_table_data(self, file_path: str, data: list[list[str]], format: str): # Logic for saving table data in a specified format pass4. TableHeaderManager
Handles operations related to table headers.
class TableHeaderManager: """Handles operations related to table headers.""" def __init__(self, app: TableApp): self.app = app def rename_headers(self): # Logic for renaming headers pass5. TableRenameManager
Handles renaming of tables.
class TableRenameManager: """Handles operations for table renaming.""" def __init__(self, app: TableApp): self.app = app def begin_rename(self, table_name: str): # Logic for starting table renaming pass def end_rename(self, old_name: str): # Logic for finalizing table renaming pass def update_table_name(self, old_name: str, new_name: str): # Logic for updating table name pass def cancel_rename(self): # Logic for canceling renaming operation passIntegration
You'll need to integrate these classes back into the existing structure. You may need a facade or a higher-level manager to coordinate between these classes, which could be the original
TableManager(now acting as a composition of these new classes).class TableManager: """Main class managing all aspects of table operations.""" def __init__(self, app: TableApp): self.creation_manager = TableCreationManager(app) self.loading_manager = TableLoadingManager(app) self.file_manager = TableFileManager(app) self.header_manager = TableHeaderManager(app) self.rename_manager = TableRenameManager(app)This refactoring splits responsibilities into distinct, focused classes, which aligns with the Single Responsibility Principle (SRP) and enhances the maintainability, testability, and readability of the code.
- User
Print the new code in full
- Assistant
Certainly! Below is the new code after refactoring the
TableManagerclass into several distinct classes, each responsible for a different aspect of table management.from typing import Optional, List import tkinter as tk from tkinter import messagebox, filedialog, simpledialog import csv import json from pathlib import Path class TableCreationManager: """Handles creation and addition of new tables.""" def __init__(self, app: 'TableApp'): self.app = app def create_new_table(self): """Create a new table.""" existing_numbers = [ int(name.split(" ")[1]) for name in self.app.data_manager.tables_data if name.startswith("Table ") and name.split(" ")[1].isdigit() ] next_number = max(existing_numbers, default=0) + 1 table_name = f"Table {next_number}" self.add_table(table_name) self.app.loading_manager.load_selected_table(table_name) def add_table(self, table_name: str, data: List[List[str]] = None, headers: Optional[List[str]] = None): """Add a new table.""" if headers: self.app.data_manager.headers[table_name] = headers else: default_headers = [ "Column 1", "Column 2", "Column 3", "Column 4", "Column 5", ] self.app.data_manager.headers[table_name] = default_headers self.app.data_manager.tables_data[table_name] = { "headers": self.app.data_manager.headers[table_name], "data": data or [ ["" for _ in range(len(self.app.data_manager.headers[table_name]))] for _ in range(10) ], } self.app.sidebar.create_table_label(table_name) self.app.data_manager.save_data() def ensure_unique_table_name(self, table_name: str) -> str: """Ensure table name is unique.""" original_name = table_name counter = 1 while table_name in self.app.data_manager.tables_data: table_name = f"{original_name} (New {counter})" counter += 1 return table_name class TableLoadingManager: """Handles loading, editing and deleting operations on tables.""" def __init__(self, app: 'TableApp'): self.app = app def load_selected_table(self, table_name: str): """Display selected table.""" if self.app.current_sheet: self.app.current_sheet.pack_forget() self.app.current_sheet.destroy() self.app.current_sheet = None if self.app.sidebar.selected_table_label: try: self.app.sidebar.selected_table_label.config( bg=self.app.colors["button"] ) except tk.TclError: self.app.sidebar.selected_table_label = None if table_name not in self.app.data_manager.tables_data: messagebox.showerror("Error", f"Table '{table_name}' does not exist.") self.app.current_table_name = None self.app.sidebar.selected_table_label = None return table_info = self.app.data_manager.tables_data[table_name] headers = table_info["headers"] data = table_info["data"] try: sheet = Sheet( self.app.table_frame, data=data, show_table=True, headers=headers, font=self.app.fonts["tksheet"], header_font=self.app.fonts["tksheet"], auto_resize_columns=True, ) sheet.set_options( table_fg=self.app.colors["text"], header_fg=self.app.colors["text"] ) sheet.enable_bindings() sheet.extra_bindings( [ ("end_edit_cell", self.on_cell_edit), ("end_delete_columns", self.on_columns_deleted), ] ) sheet.pack(expand=True, fill="both") self.app.current_sheet = sheet self.app.current_table_name = table_name if self.app.header.table_name_label: self.app.header.table_name_label.config(text=self.app.current_table_name) else: self.app.header.table_name_label = tk.Label( self.app.root, text=self.app.current_table_name, bg=self.app.colors["background"], fg=self.app.colors["text"], font=self.app.fonts["header_info"], ) self.app.header.table_name_label.grid( row=0, column=0, padx=(60, 10), pady=(5, 0), sticky="nw" ) label = self.app.sidebar.table_labels.get(table_name) if label: self.app.sidebar.selected_table_label = label try: self.app.sidebar.selected_table_label.config( bg=self.app.colors["button_selected"] ) except tk.TclError: self.app.sidebar.selected_table_label = None messagebox.showerror( "Error", f"Failed to update the label for '{table_name}'." ) else: self.app.sidebar.selected_table_label = None messagebox.showerror("Error", f"Label for '{table_name}' not found.") self.app.filter_controls.filter_header_var.set("All") self.app.filter_controls.filter_header_dropdown["values"] = ["All"] + headers self.app.filter_controls.filter_option_var.set("contains") self.app.filter_controls.update_filter_text_state() self.app.apply_filter() except Exception as e: messagebox.showerror( "Sheet Error", f"Failed to load table '{table_name}': {e}" ) self.app.current_table_name = None self.app.sidebar.selected_table_label = None def on_cell_edit(self, event=None): """Handle cell edits.""" if self.app.current_table_name and self.app.current_sheet: sheet_data = self.app.current_sheet.get_sheet_data() for idx, row in enumerate(sheet_data): if idx < len(self.app.displayed_row_indices): data_idx = self.app.displayed_row_indices[idx] self.app.data_manager.tables_data[self.app.current_table_name][ "data" ][data_idx] = row else: # Handle new rows by appending to the underlying data self.app.data_manager.tables_data[self.app.current_table_name][ "data" ].append(row) self.app.data_manager.save_data() def on_columns_deleted(self, event): """Handle column deletion and update filter headers.""" if not self.app.current_table_name or not self.app.current_sheet: return new_headers = self.app.current_sheet.headers() self.app.data_manager.headers[self.app.current_table_name] = new_headers self.app.filter_controls.filter_header_dropdown["values"] = ["All"] + new_headers self.app.filter_controls.filter_header_var.set("All") self.app.filter_controls.filter_option_var.set("contains") self.app.filter_controls.filter_text_var.set("") self.app.filter_controls.filter_text_entry.config(state="normal") self.app.apply_filter() def delete_table(self): """Delete selected table.""" if ( not self.app.current_table_name or self.app.current_table_name not in self.app.data_manager.tables_data ): messagebox.showwarning( "No Table Selected", "Please select a valid table to delete." ) return if messagebox.askyesno( "Delete Table", f"Are you sure you want to delete the table '{self.app.current_table_name}'?", ): self.remove_table(self.app.current_table_name) def remove_table(self, table_name: str): """Remove a table.""" if self.app.current_table_name == table_name and self.app.current_sheet: self.app.current_sheet.destroy() self.app.current_sheet = None label = self.app.sidebar.table_labels.get(table_name) if label: label.destroy() if table_name in self.app.data_manager.tables_data: del self.app.data_manager.tables_data[table_name] if table_name in self.app.data_manager.headers: del self.app.data_manager.headers[table_name] if table_name in self.app.sidebar.table_labels: del self.app.sidebar.table_labels[table_name] self.app.current_table_name = None self.app.sidebar.selected_table_label = None self.app.data_manager.save_data() self.app.sidebar.sort_table_labels() class TableFileManager: """Handles import and export operations for table data.""" def __init__(self, app: 'TableApp'): self.app = app def import_file(self): """Import table from file.""" file_path = filedialog.askopenfilename( title="Import File", filetypes=[ ("All Supported Files", "*.json *.csv"), ("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.") if ( not data or not isinstance(data, list) or not all(isinstance(row, list) for row in data) ): raise ValueError("Invalid data format in the file.") headers, table_data = data[0], data[1:] self.app.creation_manager.add_table_from_data(file_path, headers, table_data) except Exception as e: messagebox.showerror("File Import Error", str(e)) def export_table(self): """Export current table to file.""" if ( not self.app.current_table_name or self.app.current_table_name not in self.app.data_manager.tables_data ): messagebox.showwarning( "No Table Selected", "Please select a table to export." ) return file_path = filedialog.asksaveasfilename( title="Export File", defaultextension=".json", filetypes=[("JSON files", "*.json"), ("CSV files", "*.csv")], initialfile=self.app.current_table_name, ) if not file_path: return try: data = [ self.app.data_manager.headers[self.app.current_table_name] ] + self.app.data_manager.tables_data[self.app.current_table_name]["data"] if file_path.endswith(".csv"): self.save_table_data(file_path, data, "csv") elif file_path.endswith(".json"): with open(file_path, "w", encoding="utf-8") as file: json.dump(data, file, indent=4) else: raise ValueError("Unsupported file format.") self.app.data_manager.save_data() messagebox.showinfo( "Export Successful", f"Table '{self.app.current_table_name}' has been exported successfully.", ) except Exception as e: messagebox.showerror( "Export Failed", f"An error occurred during export: {e}" ) def save_table_data(self, file_path: str, data: List[List[str]], format: str): """Save table data in specified format.""" match format: case "csv": with open(file_path, "w", newline="", encoding="utf-8") as file: csv.writer(file).writerows(data) case "json": with open(file_path, "w", encoding="utf-8") as file: json.dump(data, file, indent=4) case _: raise ValueError("Unsupported file format.") class TableHeaderManager: """Handles operations related to table headers.""" def __init__(self, app: 'TableApp'): self.app = app def rename_headers(self): """Rename table headers.""" if not self.app.current_table_name: messagebox.showwarning( "No Table Selected", "Please select a table to rename headers." ) return current_headers = self.app.data_manager.headers[self.app.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(",")] if not header_list: messagebox.showerror("Invalid Headers", "Header list cannot be empty.") return self.app.data_manager.headers[self.app.current_table_name] = header_list self.app.data_manager.tables_data[self.app.current_table_name][ "headers" ] = header_list if self.app.current_sheet: try: self.app.current_sheet.headers(header_list) except tk.TclError as e: messagebox.showerror("Error", f"Failed to rename headers: {e}") self.app.filter_controls.filter_header_var.set("All") self.app.filter_controls.filter_header_dropdown["values"] = [ "All" ] + header_list self.app.apply_filter() self.app.data_manager.save_data() class TableRenameManager: """Handles operations for table renaming.""" def __init__(self, app: 'TableApp'): self.app = app def begin_rename(self, table_name: str): """Start renaming a table.""" if table_name not in self.app.sidebar.table_labels: messagebox.showerror("Error", f"Table '{table_name}' not found.") return label = self.app.sidebar.table_labels[table_name] self.cancel_rename() self.app.sidebar.rename_entry = tk.Entry( self.app.sidebar.table_labels_frame, bg=label.cget("bg"), fg=self.app.colors["text"], relief="flat", ) self.app.sidebar.rename_entry.insert(0, table_name) self.app.sidebar.rename_entry.place( x=label.winfo_x(), y=label.winfo_y(), width=label.winfo_width(), height=label.winfo_height(), ) self.app.sidebar.rename_entry.focus() self.app.sidebar.rename_entry.select_range(0, tk.END) self.app.sidebar.rename_entry.bind( "<Return>", lambda event: self.end_rename(table_name) ) self.app.sidebar.rename_entry.bind("<FocusOut>", lambda event: self.cancel_rename()) def end_rename(self, old_name: str): """Finalize table renaming.""" new_name = self.app.sidebar.rename_entry.get().strip() if not new_name: messagebox.showerror("Invalid Name", "Table name cannot be empty.") self.app.sidebar.rename_entry.focus_set() return if new_name in self.app.data_manager.tables_data and new_name != old_name: messagebox.showerror( "Duplicate Name", f"A table named '{new_name}' already exists." ) self.app.sidebar.rename_entry.focus_set() return if new_name != old_name: self.update_table_name(old_name, new_name) self.app.loading_manager.load_selected_table(new_name) self.cancel_rename() def update_table_name(self, old_name: str, new_name: str): """Update table name and resources.""" self.app.data_manager.tables_data[new_name] = self.app.data_manager.tables_data.pop( old_name ) self.app.data_manager.headers[new_name] = self.app.data_manager.headers.pop( old_name ) label = self.app.sidebar.table_labels.pop(old_name) label.config(text=new_name) label.bind( "<Button-1>", lambda event: self.app.loading_manager.load_selected_table(new_name) ) label.bind( "<Double-1>", lambda event: self.begin_rename(new_name) ) self.app.sidebar.table_labels[new_name] = label if self.app.sidebar.selected_table_label == label: try: label.config(bg=self.app.colors["button_selected"]) except tk.TclError: pass self.app.data_manager.save_data() self.app.sidebar.sort_table_labels() def cancel_rename(self): """Cancel rename operation.""" if self.app.sidebar.rename_entry: self.app.sidebar.rename_entry.destroy() self.app.sidebar.rename_entry = None class TableManager: """Main class managing all aspects of table operations.""" def __init__(self, app: 'TableApp'): self.creation_manager = TableCreationManager(app) self.loading_manager = TableLoadingManager(app) self.file_manager = TableFileManager(app) self.header_manager = TableHeaderManager(app) self.rename_manager = TableRenameManager(app)To effectively use these classes, you should integrate the methods from the individual managers into the interface provided by the
TableManagerclass. This can mean calling methods on the respective manager classes by accessing attributes likeself.creation_managerfrom withinTableManageror directly replacing method calls in other parts of the app to use these managers. Each class is now focusing on specific responsibilities, making the code more modular and easier to manage.