You are a Python 3.12 programmer, capable of analyzing problems in depth and…
- User
SYSTEM: You are a Python 3.12 programmer, capable of analyzing problems in depth and explaining solutions in a clear and concise manner. Your responses prioritize code efficiency, readability, and simplicity. You leverage the latest Python features. When addressing tasks, you break them down into clear steps and present only essential information, ensuring users receive focused, expert guidance tailored to their needs. You only print the parts of the code you changed in a way that makes them easy to copy paste in the code base. Remember the code uses tksheet 7. Lets think step by step. USER: Improve the automatic column width adjustment. The Column width should be adjusted so that all the content in the columns is visible. When all the columns do not fit the window let the columns go over the window. Also when all columns combined are shorter than the window adjust the columns to fit the window. Python 3.12 Code: class TableDisplayManager: """Handles loading and displaying tables and related events."""
def __init__(self, app: 'TableApp'): self.app = app def load_selected_table(self, table_name: str) -> None: try: 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: self.app.sidebar.selected_table_label.config(bg=self.app.colors["button"]) 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 return table_info = self.app.data_manager.tables_data[table_name] headers = self.auto_rename_empty_headers(table_info["headers"]) table_info["headers"] = headers data = table_info["data"] data_types = table_info.get("data_types", []) if self.app.filter_controls: # Check if filter controls exist 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.update_filter_text_state() self.app.filter_controls.reset_row_indices() 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.enable_bindings("edit_header") 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_edit), ("end_delete_columns", self.on_columns_deleted), ("end_insert_column", self.on_columns_inserted), ("cell_select", self.on_cell_select), ("end_edit_header", self.on_edit), ("delete", self.on_edit), ("end_insert_row", self.on_edit), ("end_cut", self.on_edit), ("end_paste", self.on_edit), ("end_delete_rows", self.on_edit), ] ) sheet.pack(expand=True, fill="both") self.app.current_sheet = sheet self.app.current_table_name = table_name if data_types: self.apply_column_data_types(data_types) if not self.app.header.table_name_label: 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" ) else: self.app.header.table_name_label.config(text=self.app.current_table_name) if label := self.app.sidebar.table_labels.get(table_name): self.app.sidebar.selected_table_label = label label.config(bg=self.app.colors["button_selected"]) else: messagebox.showerror("Error", f"Label for '{table_name}' not found.") self.app.sidebar.selected_table_label = None 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 auto_rename_empty_headers(self, headers: list[str]) -> list[str]: """Automatically rename empty column headers to 'Column X' where X is the next available number.""" max_column_num = 0 for header in headers: if header.startswith("Column "): try: num = int(header.split(" ")[1]) max_column_num = max(max_column_num, num) except (ValueError, IndexError): continue counter = max_column_num + 1 new_headers = [] for header in headers: if not header or header.isspace(): new_headers.append(f"Column {counter}") counter += 1 else: new_headers.append(header) return new_headers def apply_column_data_types(self, data_types: list) -> None: """Apply column data types and format the sheet.""" if not self.app.current_sheet: return sheet = self.app.current_sheet sheet.del_all_formatting() if checkboxes := sheet.get_checkboxes(): for key in list(checkboxes.keys()): sheet.del_checkbox(key) for col_idx, dtype in enumerate(data_types): column_letter = num2alpha(col_idx) match dtype: case 'integer': sheet.format(column_letter, formatter_options=int_formatter(nullable=True, invalid_value='')) case 'float': sheet.format(column_letter, formatter_options=float_formatter(nullable=True, invalid_value='')) case 'boolean': sheet.checkbox(column_letter, checked=None, check_function=self.on_checkbox_click) num_rows = len(sheet.get_sheet_data()) cells_to_highlight = [(row, col_idx) for row in range(num_rows)] sheet.highlight_cells(cells=cells_to_highlight, fg=self.app.colors["checkbox"]) case 'string': continue case _: continue sheet.reapply_formatting() def on_checkbox_click(self, event: dict) -> None: """Handle checkbox click events and update data.""" if not self.app.current_table_name or not self.app.current_sheet: return row, col, new_value = event['row'], event['column'], event['value'] if row < len(self.app.displayed_row_indices): data_row_index = self.app.displayed_row_indices[row] self.app.data_manager.tables_data[self.app.current_table_name]["data"][data_row_index][col] = new_value self.app.data_manager.save_data() else: print(f"Row index {row} out of range for displayed_row_indices") def on_edit(self, event=None): """Handle both cell and header edits and save the updated data.""" self.process_and_save_current_sheet_data() def on_columns_deleted(self, event: dict) -> None: """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 deleted_columns = event.get('columns', []) data_types = self.app.data_manager.tables_data[self.app.current_table_name].get("data_types", []) for col_idx in sorted(deleted_columns, reverse=True): if col_idx < len(data_types): del data_types[col_idx] self.app.data_manager.tables_data[self.app.current_table_name]["data_types"] = data_types self.app.data_manager.save_data() 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 on_columns_inserted(self, event: dict) -> None: """Handle columns inserted and update data types and headers.""" if not self.app.current_table_name or not self.app.current_sheet: return current_headers = list(self.app.current_sheet.headers()) current_headers = self.auto_rename_empty_headers(current_headers) self.app.current_sheet.headers(current_headers) inserted_columns = event.get('columns', []) data_types = self.app.data_manager.tables_data[self.app.current_table_name].get("data_types", []) for col_idx in inserted_columns: data_types.insert(col_idx, 'string') self.app.data_manager.tables_data[self.app.current_table_name]["data_types"] = data_types self.app.data_manager.tables_data[self.app.current_table_name]["headers"] = current_headers self.app.data_manager.save_data() self.app.filter_controls.filter_header_dropdown["values"] = ["All"] + current_headers def on_cell_select(self, event: dict) -> None: """Handle cell selection to give focus to checkboxes.""" if not self.app.current_table_name or not self.app.current_sheet: return row, col = event.row, event.column checkboxes = self.app.current_sheet.get_checkboxes() if (row, col) not in checkboxes: return self.app.current_sheet.focus_set() def process_and_save_current_sheet_data(self) -> None: """Processes sheet data with type conversion and saves to data manager.""" if not (current_table := self.app.current_table_name) or not self.app.current_sheet: return if not (table_info := self.app.data_manager.tables_data.get(current_table)): return sheet_data = self.app.current_sheet.get_sheet_data() data_types = table_info.get("data_types", []) table_data = table_info["data"] table_data.clear() table_data.extend([ [self._convert_cell(cell, data_types[i] if i < len(data_types) else "string") for i, cell in enumerate(row)] for row in sheet_data ]) self.app.data_manager.save_data() def _convert_cell(self, cell: str, dtype: str) -> Union[str, int, float, bool, None]: """Converts cell value to specified data type with error handling.""" if not cell or cell is None: return { 'integer': None, 'float': None, 'boolean': False }.get(dtype, '') type_converters = { 'integer': lambda x: int(x), 'float': lambda x: float(x), 'boolean': lambda x: str(x).lower() in ('true', '1', 'yes'), 'string': lambda x: x } try: return type_converters.get(dtype, type_converters['string'])(cell) except (ValueError, TypeError): return None if dtype in ('integer', 'float') else cell - Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.