Why does adding and deleting of columns work properly in code 1 but not in code 2? Fix code two based on what you learned from code 1. Code 1: import ctypes
import csv
import json
import re
import tkinter as tk
from pathlib import Path
from tkinter import filedialog, messagebox, simpledialog, ttk
from typing import Any, Optional
from tksheet import Sheet
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}")
def custom_filter_design(master, style: ttk.Style, headers=None, filter_types=None, filter_font=None, filter_combobox_font=None, colors=None):
"""Creates a custom filter frame with all components."""
filter_frame = ttk.Frame(master, style="Custom.TFrame")
def setup_ui(self):
"""Set up the user interface with a 3x2 grid layout."""
self.root.grid_rowconfigure(0, weight=0)
self.root.grid_rowconfigure(1, weight=1)
def _create_and_configure_header_frame(self) -> tk.Frame:
"""Create and configure the main header frame."""
header_frame = self._create_frame(parent=self.root, width=None, bg=self.colors["background"])
header_frame.grid(row=0, column=1, columnspan=2, sticky='ew')
header_frame.config(height=self.dimensions["header_height"])
header_frame.grid_propagate(False)
for i in range(2):
header_frame.grid_rowconfigure(i, weight=0)
for i in range(5):
weight = 1 if i == 4 else 0
header_frame.grid_columnconfigure(i, weight=weight)
return header_frame
def update_filter_text_state(self, event=None):
"""Enable or disable the filter text entry based on filter option."""
option = self.filter_option_var.get()
if option in ["is empty", "is not empty"]:
self.filter_text_var.set("")
self.filter_text_entry.config(state='disabled')
self.apply_filter()
else:
self.filter_text_entry.config(state='normal')
def _on_canvas_configure(self, event):
"""Update the table_labels_frame width to match the canvas width."""
self.canvas.itemconfig(self.table_labels_window, width=event.width)
def _add_scrollable_canvas(self, sidebar: tk.Frame):
"""Add scrollable canvas for table labels within a single frame."""
scrollable_container = self._create_frame(
parent=sidebar,
width=self.dimensions["sidebar_width"],
bg=self.colors["sidebar"]
)
scrollable_container.grid(row=1, column=0, sticky='nsew', padx=10, pady=10)
scrollable_container.columnconfigure(0, weight=1)
scrollable_container.rowconfigure(0, weight=1)
def _on_mouse_wheel(self, event):
"""Handle mouse wheel scrolling only if scrollbar is visible."""
if self.scrollbar.winfo_viewable():
self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
def _update_scrollbar(self, scrollbar_frame, canvas, scrollbar):
"""Update scrollbar visibility based on content size."""
canvas.update_idletasks()
canvas_height = scrollbar_frame.winfo_height()
content_height = self.table_labels_frame.winfo_reqheight()
def sort_table_labels(self):
"""Sort table labels with numeric names first, then alphabetic, then alphanumeric."""
def sort_key(name):
# Category 1: Starts with digits (e.g., "1. Movies")
m = re.match(r'^(\d+)', name)
if m:
return (1, int(m.group(1)))
# Category 3: Starts with letters followed by digits (e.g., "T1", "T2")
m = re.match(r'^([A-Za-z]+)(\d+)', name)
if m:
return (3, m.group(1).lower(), int(m.group(2)))
# Category 2: Starts with letters only (e.g., "a", "b", "c")
m = re.match(r'^([A-Za-z]+)', name)
if m:
return (2, m.group(1).lower())
# Category 4: Any other names
return (4, name.lower())
# Sort the table names using the defined sort key
sorted_tables = sorted(self.tables_data.keys(), key=sort_key)
# Re-pack the labels in the sorted order
for table_name in sorted_tables:
label = self.table_labels.get(table_name)
if label:
label.pack_forget()
label.pack(fill='x', padx=0, pady=5, expand=True)
def create_new_table(self):
"""Create a new table."""
existing_numbers = [int(name.split(" ")[1]) for name in self.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 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 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.tables_data:
table_name = f"{original_name} (New {counter})"
counter += 1
return table_name
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 export_table(self):
"""Export current table to file."""
if not self.current_table_name or self.current_table_name not in self.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.current_table_name)
if not file_path:
return
try:
data = [self.headers[self.current_table_name]] + self.tables_data[self.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.save_data()
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 add_table(self, table_name: str, data: list[list[str]] | None = None, headers: Optional[list[str]] = None):
"""Add a new table."""
if headers:
self.headers[table_name] = headers
else:
default_headers = ["Column 1", "Column 2", "Column 3", "Column 4", "Column 5"]
self.headers[table_name] = default_headers
self.tables_data[table_name] = {"headers": self.headers[table_name], "data": data or [["" for _ in range(len(self.headers[table_name]))] for _ in range(10)]}
self.create_table_label(table_name)
self.save_data()
def delete_table(self):
"""Delete selected table."""
if not self.current_table_name or self.current_table_name not in self.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.current_table_name}'?"):
self.remove_table(self.current_table_name)
def on_columns_deleted(self, event):
"""Handle column deletion and update filter headers."""
if not self.current_table_name or not self.current_sheet:
return
new_headers = self.current_sheet.headers()
self.headers[self.current_table_name] = new_headers
self.filter_header_dropdown['values'] = ["All"] + new_headers
self.filter_header_var.set("All")
self.filter_option_var.set("contains")
self.filter_text_var.set("")
self.filter_text_entry.config(state='normal')
self.apply_filter()
def remove_table(self, table_name: str):
"""Remove a table."""
if self.current_table_name == table_name and self.current_sheet:
self.current_sheet.destroy()
self.current_sheet = None
label = self.table_labels.get(table_name)
if label:
label.destroy()
if table_name in self.tables_data:
del self.tables_data[table_name]
if table_name in self.headers:
del self.headers[table_name]
if table_name in self.table_labels:
del self.table_labels[table_name]
self.current_table_name = None
self.selected_table_label = None
self.save_data()
self.sort_table_labels()
def load_tables(self):
"""Load tables from file."""
if not self.save_file_path.exists():
return
try:
with self.save_file_path.open('r', encoding='utf-8') as file:
all_data = json.load(file)
except Exception as e:
messagebox.showerror("Load Error", f"Failed to load tables: {e}")
return
for table_name, data in all_data.items():
if not isinstance(data, list) or not data:
continue
headers, table_data = data[0], data[1:]
self.headers[table_name] = headers
self.tables_data[table_name] = {"headers": headers, "data": table_data}
self.create_table_label(table_name)
self.sort_table_labels()
if table_name not in self.tables_data:
messagebox.showerror("Error", f"Table '{table_name}' does not exist.")
self.current_table_name = None
self.selected_table_label = None
return
table_info = self.tables_data[table_name]
headers = table_info["headers"]
data = table_info["data"]
try:
sheet = Sheet(
self.table_frame,
data=data,
show_table=True,
headers=headers,
font=self.fonts["tksheet"],
header_font=self.fonts["tksheet"],
auto_resize_columns=True
)
sheet.set_options(table_fg=self.colors["text"], header_fg=self.colors["text"])
sheet.enable_bindings()
sheet.extra_bindings([
("end_edit_cell", self.on_cell_edit),
("end_delete_columns", self.on_columns_deleted) # Added binding for column deletion
])
sheet.pack(expand=True, fill='both')
self.current_sheet = sheet
self.current_table_name = table_name
if self.table_name_label:
self.table_name_label.config(text=self.current_table_name)
else:
self.table_name_label = tk.Label(
self.root,
text=self.current_table_name,
bg=self.colors["background"],
fg=self.colors["text"],
font=self.fonts["header_info"]
)
self.table_name_label.grid(row=0, column=0, padx=(60, 10), pady=(5, 0), sticky='nw')
label = self.table_labels.get(table_name)
if label:
self.selected_table_label = label
try:
self.selected_table_label.config(bg=self.colors["button_selected"])
except tk.TclError:
self.selected_table_label = None
messagebox.showerror("Error", f"Failed to update the label for '{table_name}'.")
else:
self.selected_table_label = None
messagebox.showerror("Error", f"Label for '{table_name}' not found.")
self.filter_header_var.set("All")
self.filter_header_dropdown['values'] = ["All"] + headers
self.filter_option_var.set("contains")
self.update_filter_text_state()
self.apply_filter()
except Exception as e:
messagebox.showerror("Sheet Error", f"Failed to load table '{table_name}': {e}")
self.current_table_name = None
self.selected_table_label = None
def on_cell_edit(self, event=None):
"""Handle cell edits."""
if self.current_table_name and self.current_sheet:
sheet_data = self.current_sheet.get_sheet_data()
for idx, row in enumerate(sheet_data):
if idx < len(self.displayed_row_indices):
data_idx = self.displayed_row_indices[idx]
self.tables_data[self.current_table_name]["data"][data_idx] = row
else:
# Added: Handle new rows by appending to the underlying data
self.tables_data[self.current_table_name]["data"].append(row)
self.save_data()
def save_data(self):
"""Save all tables data."""
all_data = {}
for table_name, table_info in self.tables_data.items():
all_data[table_name] = [table_info["headers"]] + table_info["data"]
try:
with self.save_file_path.open('w', encoding='utf-8') as file:
json.dump(all_data, file, indent=4)
except Exception as e:
print(f"Error saving data: {e}")
def apply_filter(self, event=None):
"""Apply filter to table data based on selected criteria."""
if not self.current_table_name or not self.current_sheet:
return
header = self.filter_header_var.get()
option = self.filter_option_var.get()
text = self.filter_text_var.get().lower()
original_data = self.tables_data[self.current_table_name]["data"]
def row_matches(row):
if header == "All":
cells = row
target_indices = range(len(cells))
else:
try:
target_indices = [self.headers[self.current_table_name].index(header)]
except ValueError:
return False
conditions = {
"is": lambda cell, text: cell == text,
"is not": lambda cell, text: cell != text,
"contains": lambda cell, text: text in cell,
"does not contain": lambda cell, text: text not in cell,
"starts with": lambda cell, text: cell.startswith(text),
"ends with": lambda cell, text: cell.endswith(text),
"is empty": lambda cell, _: cell == "",
"is not empty": lambda cell, _: cell != ""
}
for idx in target_indices:
cell = str(row[idx]).lower()
if conditions.get(option, lambda _, __: False)(cell, text):
return True
return False
# Collect both filtered data and their original indices
filtered_data = []
self.displayed_row_indices = []
for i, row in enumerate(original_data):
if row_matches(row):
filtered_data.append(row)
self.displayed_row_indices.append(i)
try:
self.current_sheet.set_sheet_data(filtered_data)
except tk.TclError as e:
print(f"Error applying filter: {e}")
def rename_headers(self):
"""Rename table headers."""
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(',')]
if not header_list:
messagebox.showerror("Invalid Headers", "Header list cannot be empty.")
return
self.headers[self.current_table_name] = header_list
self.tables_data[self.current_table_name]["headers"] = header_list
if self.current_sheet:
try:
self.current_sheet.headers(header_list)
except tk.TclError as e:
messagebox.showerror("Error", f"Failed to rename headers: {e}")
def setup_ui(self):
"""Set up the user interface with a 3x2 grid layout."""
self.root.grid_rowconfigure(0, weight=0)
self.root.grid_rowconfigure(1, weight=1)
def _create_and_configure_header_frame(self) -> tk.Frame:
"""Create and configure the main header frame."""
header_frame = self._create_frame(parent=self.root, width=None, bg=self.colors["background"])
header_frame.grid(row=0, column=1, columnspan=2, sticky='ew')
header_frame.config(height=self.dimensions["header_height"])
header_frame.grid_propagate(False)
for i in range(2):
header_frame.grid_rowconfigure(i, weight=0)
for i in range(5):
weight = 1 if i == 4 else 0
header_frame.grid_columnconfigure(i, weight=weight)
return header_frame
def update_filter_text_state(self, event=None):
"""Enable or disable the filter text entry based on filter option."""
option = self.filter_option_var.get()
if option in ["is empty", "is not empty"]:
self.filter_text_var.set("")
self.filter_text_entry.config(state='disabled')
self.apply_filter()
else:
self.filter_text_entry.config(state='normal')
def _on_canvas_configure(self, event):
"""Update the table_labels_frame width to match the canvas width."""
self.canvas.itemconfig(self.table_labels_window, width=event.width)
def _add_scrollable_canvas(self, sidebar: tk.Frame):
"""Add scrollable canvas for table labels within a single frame."""
scrollable_container = self._create_frame(
parent=sidebar,
width=self.dimensions["sidebar_width"],
bg=self.colors["sidebar"]
)
scrollable_container.grid(row=1, column=0, sticky='nsew', padx=10, pady=10)
scrollable_container.columnconfigure(0, weight=1)
scrollable_container.rowconfigure(0, weight=1)
def _on_mouse_wheel(self, event):
"""Handle mouse wheel scrolling only if scrollbar is visible."""
if self.scrollbar.winfo_viewable():
self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
def _update_scrollbar(self, scrollbar_frame, canvas, scrollbar):
"""Update scrollbar visibility based on content size."""
canvas.update_idletasks()
canvas_height = scrollbar_frame.winfo_height()
content_height = self.table_labels_frame.winfo_reqheight()
def sort_table_labels(self):
"""Sort table labels with numeric names first, then alphabetic, then alphanumeric."""
def sort_key(name):
# Category 1: Starts with digits (e.g., "1. Movies")
m = re.match(r'^(\d+)', name)
if m:
return (1, int(m.group(1)))
# Category 3: Starts with letters followed by digits (e.g., "T1", "T2")
m = re.match(r'^([A-Za-z]+)(\d+)', name)
if m:
return (3, m.group(1).lower(), int(m.group(2)))
# Category 2: Starts with letters only (e.g., "a", "b", "c")
m = re.match(r'^([A-Za-z]+)', name)
if m:
return (2, m.group(1).lower())
# Category 4: Any other names
return (4, name.lower())
# Sort the table names using the defined sort key
sorted_tables = sorted(self.tables_data.keys(), key=sort_key)
# Re-pack the labels in the sorted order
for table_name in sorted_tables:
label = self.table_labels.get(table_name)
if label:
label.pack_forget()
label.pack(fill='x', padx=0, pady=5, expand=True)
def create_new_table(self):
"""Create a new table."""
existing_numbers = [int(name.split(" ")[1]) for name in self.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 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:
reader = csv.reader(csvfile)
data = list(reader)
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)
headers_with_types = [{"name": h, "type": "string"} for h in headers]
self.add_table(table_name, data=table_data, headers=headers_with_types)
self.load_selected_table(table_name)
self.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.tables_data:
table_name = f"{original_name} (New {counter})"
counter += 1
return table_name
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 export_table(self):
"""Export current table to file."""
if not self.current_table_name or self.current_table_name not in self.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.current_table_name)
if not file_path:
return
try:
if file_path.endswith('.csv'):
# Extract header names
headers = [col['name'] for col in self.headers[self.current_table_name]]
# Convert all data to strings
data = [headers] + [[str(cell) for cell in row] for row in self.tables_data[self.current_table_name]["data"]]
self.save_table_data(file_path, data, 'csv')
elif file_path.endswith('.json'):
# Prepare data with headers (including types)
headers = self.headers[self.current_table_name]
data = [headers] + self.tables_data[self.current_table_name]["data"]
with open(file_path, 'w', encoding='utf-8') as file:
json.dump(data, file, indent=4)
else:
raise ValueError("Unsupported file format.")
self.save_data()
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 add_table(self, table_name: str, data: list[list[str]] | None = None, headers: Optional[list[dict[str, str]]] = None):
"""Add a new table."""
if headers:
self.headers[table_name] = headers
else:
default_headers = [
{"name": "Column 1", "type": "string"},
{"name": "Column 2", "type": "string"},
{"name": "Column 3", "type": "string"},
{"name": "Column 4", "type": "string"},
{"name": "Column 5", "type": "string"}
]
self.headers[table_name] = default_headers
self.tables_data[table_name] = {"headers": self.headers[table_name], "data": data or [["" for _ in range(len(self.headers[table_name]))] for _ in range(10)]}
self.create_table_label(table_name)
self.save_data()
def delete_table(self):
"""Delete selected table."""
if not self.current_table_name or self.current_table_name not in self.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.current_table_name}'?"):
self.remove_table(self.current_table_name)
def on_columns_deleted(self, event):
"""Handle column deletion and update filter headers."""
if not self.current_table_name or not self.current_sheet:
return
new_headers = self.current_sheet.headers()
# Since the user might have deleted columns, we need to remove them from headers
# Assuming that the order of headers in self.headers matches self.current_sheet
self.headers[self.current_table_name] = [{"name": h, "type": col['type']} for h, col in zip(new_headers, self.headers[self.current_table_name]) if h]
self.filter_header_dropdown['values'] = ["All"] + [col['name'] for col in self.headers[self.current_table_name]]
self.filter_header_var.set("All")
self.filter_option_var.set("contains")
self.filter_text_var.set("")
self.filter_text_entry.config(state='normal')
self.apply_filter()
self.save_data()
def remove_table(self, table_name: str):
"""Remove a table."""
if self.current_table_name == table_name and self.current_sheet:
self.current_sheet.pack_forget()
self.current_sheet.destroy()
self.current_sheet = None
label = self.table_labels.get(table_name)
if label:
label.destroy()
if table_name in self.tables_data:
del self.tables_data[table_name]
if table_name in self.headers:
del self.headers[table_name]
if table_name in self.table_labels:
del self.table_labels[table_name]
self.current_table_name = None
self.selected_table_label = None
self.save_data()
self.sort_table_labels()
def load_tables(self):
"""Load tables from file."""
if not self.save_file_path.exists():
return
try:
with self.save_file_path.open('r', encoding='utf-8') as file:
all_data = json.load(file)
except Exception as e:
messagebox.showerror("Load Error", f"Failed to load tables: {e}")
return
for table_name, data in all_data.items():
if not isinstance(data, list) or not data:
continue
headers, table_data = data[0], data[1:]
self.headers[table_name] = headers
# Ensure each header has 'name' and 'type'
if all(isinstance(col, dict) and 'name' in col and 'type' in col for col in headers):
pass
else:
# Legacy support: Convert list of header names to dict with type 'string'
self.headers[table_name] = [{"name": h, "type": "string"} for h in headers]
self.tables_data[table_name] = {"headers": self.headers[table_name], "data": table_data}
self.create_table_label(table_name)
self.sort_table_labels()
if table_name not in self.tables_data:
messagebox.showerror("Error", f"Table '{table_name}' does not exist.")
self.current_table_name = None
self.selected_table_label = None
return
table_info = self.tables_data[table_name]
headers = [col['name'] for col in table_info["headers"]]
data = table_info["data"]
try:
sheet = Sheet(
self.table_frame,
data=self.format_data_for_display(data),
show_table=True,
headers=headers,
font=self.fonts["tksheet"],
header_font=self.fonts["tksheet"],
auto_resize_columns=True
)
sheet.set_options(table_fg=self.colors["text"], header_fg=self.colors["text"])
sheet.enable_bindings()
sheet.extra_bindings([
("end_edit_cell", self.on_cell_edit),
("end_delete_columns", self.on_columns_deleted) # Added binding for column deletion
])
sheet.pack(expand=True, fill='both')
self.current_sheet = sheet
self.current_table_name = table_name
if self.table_name_label:
self.table_name_label.config(text=self.current_table_name)
else:
self.table_name_label = tk.Label(
self.root,
text=self.current_table_name,
bg=self.colors["background"],
fg=self.colors["text"],
font=self.fonts["header_info"]
)
self.table_name_label.grid(row=0, column=0, padx=(60, 10), pady=(5, 0), sticky='nw')
label = self.table_labels.get(table_name)
if label:
self.selected_table_label = label
try:
self.selected_table_label.config(bg=self.colors["button_selected"])
except tk.TclError:
self.selected_table_label = None
messagebox.showerror("Error", f"Failed to update the label for '{table_name}'.")
else:
self.selected_table_label = None
messagebox.showerror("Error", f"Label for '{table_name}' not found.")
self.filter_header_var.set("All")
self.filter_header_dropdown['values'] = ["All"] + headers
self.filter_option_var.set("contains")
self.update_filter_text_state()
self.apply_filter()
except Exception as e:
messagebox.showerror("Sheet Error", f"Failed to load table '{table_name}': {e}")
self.current_table_name = None
self.selected_table_label = None
def format_data_for_display(self, data: list[list[Any]]) -> list[list[str]]:
"""Convert all data to strings for display in tksheet."""
return [[str(cell) for cell in row] for row in data]
def on_cell_edit(self, event=None):
"""Handle cell edits with data type validation."""
if self.current_table_name and self.current_sheet:
sheet_data = self.current_sheet.get_sheet_data()
for idx, row in enumerate(sheet_data):
if idx < len(self.displayed_row_indices):
data_idx = self.displayed_row_indices[idx]
validated_row = []
conversion_errors = False
for col_idx, cell in enumerate(row):
col_type = self.headers[self.current_table_name][col_idx]['type']
try:
if col_type == "int":
validated_cell = int(cell)
elif col_type == "float":
validated_cell = float(cell)
elif col_type == "boolean":
validated_cell = cell.lower() in ["true", "1", "yes"]
else:
validated_cell = str(cell)
except ValueError:
messagebox.showerror("Invalid Data", f"Invalid data type for column '{self.headers[self.current_table_name][col_idx]['name']}'. Expected {col_type}.")
conversion_errors = True
break
validated_row.append(validated_cell)
if conversion_errors:
return
self.tables_data[self.current_table_name]["data"][data_idx] = validated_row
else:
# Handle new rows by appending to the underlying data
validated_row = []
conversion_errors = False
for col_idx, cell in enumerate(row):
col_type = self.headers[self.current_table_name][col_idx]['type']
try:
if col_type == "int":
validated_cell = int(cell)
elif col_type == "float":
validated_cell = float(cell)
elif col_type == "boolean":
validated_cell = cell.lower() in ["true", "1", "yes"]
else:
validated_cell = str(cell)
except ValueError:
messagebox.showerror("Invalid Data", f"Invalid data type for column '{self.headers[self.current_table_name][col_idx]['name']}'. Expected {col_type}.")
conversion_errors = True
break
validated_row.append(validated_cell)
if conversion_errors:
return
self.tables_data[self.current_table_name]["data"].append(validated_row)
self.save_data()
def save_data(self):
"""Save all tables data."""
all_data = {}
for table_name, table_info in self.tables_data.items():
all_data[table_name] = [table_info["headers"]] + table_info["data"]
try:
with self.save_file_path.open('w', encoding='utf-8') as file:
json.dump(all_data, file, indent=4)
except Exception as e:
print(f"Error saving data: {e}")
def apply_filter(self, event=None):
"""Apply filter to table data based on selected criteria."""
if not self.current_table_name or not self.current_sheet:
return
header = self.filter_header_var.get()
option = self.filter_option_var.get()
text = self.filter_text_var.get().lower()
original_data = self.tables_data[self.current_table_name]["data"]
def row_matches(row):
if header == "All":
cells = row
target_indices = range(len(cells))
else:
try:
target_indices = [self.headers[self.current_table_name].index(next(col for col in self.headers[self.current_table_name] if col['name'] == header))]
except StopIteration:
return False
conditions = {
"is": lambda cell, text: cell == text,
"is not": lambda cell, text: cell != text,
"contains": lambda cell, text: text in cell,
"does not contain": lambda cell, text: text not in cell,
"starts with": lambda cell, text: cell.startswith(text),
"ends with": lambda cell, text: cell.endswith(text),
"is empty": lambda cell, _: cell == "",
"is not empty": lambda cell, _: cell != ""
}
for idx in target_indices:
cell = str(row[idx]).lower()
if conditions.get(option, lambda _, __: False)(cell, text):
return True
return False
# Collect both filtered data and their original indices
filtered_data = []
self.displayed_row_indices = []
for i, row in enumerate(original_data):
if row_matches(row):
filtered_data.append(row)
self.displayed_row_indices.append(i)
try:
self.current_sheet.set_sheet_data(self.format_data_for_display(filtered_data))
except tk.TclError as e:
print(f"Error applying filter: {e}")
def rename_headers(self):
"""Rename table headers."""
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_str = simpledialog.askstring(
"Rename Headers",
"Enter new headers (comma-separated):",
initialvalue=", ".join([col['name'] for col in current_headers])
)
if new_headers_str:
header_list = [header.strip() for header in new_headers_str.split(',')]
if not header_list:
messagebox.showerror("Invalid Headers", "Header list cannot be empty.")
return
if len(header_list) != len(current_headers):
messagebox.showerror("Header Count Mismatch", "Number of headers must match existing columns.")
return
for col, new_name in zip(current_headers, header_list):
col['name'] = new_name
if self.current_sheet:
try:
self.current_sheet.headers([col['name'] for col in current_headers])
except tk.TclError as e:
messagebox.showerror("Error", f"Failed to rename headers: {e}")
self.filter_header_var.set("All")
self.filter_header_dropdown['values'] = ["All"] + [col['name'] for col in current_headers]
self.apply_filter()
self.save_data()
def change_data_types(self):
"""Open a dialog to change data types for each column."""
if not self.current_table_name:
messagebox.showwarning("No Table Selected", "Please select a table to change data types.")
return
change_dialog = tk.Toplevel(self.root)
change_dialog.title("Change Data Types")
change_dialog.grab_set()
columns = self.headers[self.current_table_name]
available_types = ["string", "int", "float", "boolean"]
def save_changes():
conversion_failed = False
error_messages = []
for idx, column in enumerate(columns):
selected_type = type_vars[idx].get()
if selected_type != column['type']:
old_type = column['type']
column['type'] = selected_type
# Attempt to convert existing data in this column
for row_idx, row in enumerate(self.tables_data[self.current_table_name]["data"]):
cell = row[idx]
try:
converted_cell = self.convert_cell(cell, selected_type)
self.tables_data[self.current_table_name]["data"][row_idx][idx] = converted_cell
except ValueError:
default = self.get_default_value(selected_type)
self.tables_data[self.current_table_name]["data"][row_idx][idx] = default
error_messages.append(f"Row {row_idx + 1}, Column '{column['name']}': '{cell}' cannot be converted to {selected_type}. Set to default '{default}'.")
self.save_data()
change_dialog.destroy()
# Refresh the sheet display
if self.current_sheet:
try:
sheet_data = self.format_data_for_display(self.tables_data[self.current_table_name]["data"])
self.current_sheet.set_sheet_data(sheet_data)
self.current_sheet.headers([col['name'] for col in columns])
except tk.TclError as e:
messagebox.showerror("Error", f"Failed to update sheet: {e}")
if error_messages:
messagebox.showwarning("Data Conversion Warnings", "\n".join(error_messages))
tk.Label(change_dialog, text="Select Data Types for Columns", font=self.fonts["text"]).grid(row=0, column=0, columnspan=2, pady=10)
type_vars = []
for idx, column in enumerate(columns):
tk.Label(change_dialog, text=column['name'], font=self.fonts["text"]).grid(row=idx+1, column=0, padx=10, pady=5, sticky='e')
var = tk.StringVar(value=column['type'])
type_vars.append(var)
combobox = ttk.Combobox(change_dialog, textvariable=var, values=available_types, state="readonly", font=self.fonts["filter_combobox"])
combobox.grid(row=idx+1, column=1, padx=10, pady=5, sticky='w')
save_button = tk.Button(change_dialog, text="Save", command=save_changes, font=self.fonts["text"])
save_button.grid(row=len(columns)+1, column=0, columnspan=2, pady=10)
def convert_cell(self, cell: Any, target_type: str) -> Any:
"""Convert cell to the target data type."""
if target_type == "int":
return int(cell)
elif target_type == "float":
return float(cell)
elif target_type == "boolean":
if isinstance(cell, bool):
return cell
return cell.lower() in ["true", "1", "yes"]
else:
return str(cell)
def get_default_value(self, target_type: str) -> Any:
"""Get default value based on target type."""
if target_type == "int":
return 0
elif target_type == "float":
return 0.0
elif target_type == "boolean":
return False
else:
return ""
def begin_rename(self, table_name: str):
"""Start renaming a table."""
if table_name not in self.table_labels:
messagebox.showerror("Error", f"Table '{table_name}' not found.")
return
label = self.table_labels[table_name]
self.cancel_rename()
self.rename_entry = tk.Entry(self.table_labels_frame, bg=label.cget("bg"), fg=self.colors["text"], 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('', lambda event: self.end_rename(table_name))
self.rename_entry.bind('', lambda event: self.cancel_rename())
def end_rename(self, old_name: str):
"""Finalize table renaming."""
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_data 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()
if name == "main":
set_dpi_awareness()
root = tk.Tk()
app = TableApp(root)
root.mainloop()
The issue with Code 2 not properly handling the addition and deletion of columns stems from the way headers are managed. In Code 1, headers are maintained as a simple list of strings:
self.headers: dict[str, list[str]] = {}
This straightforward structure allows for easy addition and removal of columns without complications. However, Code 2 introduces a more complex structure where headers are dictionaries containing both name and type:
While this enhancement provides additional functionality, such as managing data types for each column, it introduces challenges in synchronizing header modifications (like adding or deleting columns) with their corresponding types.
Root Cause
When columns are added or deleted in Code 2, the on_columns_deleted method attempts to update the headers while preserving their types. However, it incorrectly uses the zip function to pair new headers with existing ones. This approach fails to handle scenarios where:
Columns are added: New headers without corresponding types are not assigned a default type.
Columns are deleted: Existing types for removed headers are not properly discarded.
As a result, new columns added after initialization do not have types assigned, leading to inconsistencies and malfunctioning in operations like filtering.
Solution
To fix Code 2, we need to modify the on_columns_deleted method to:
Preserve existing types for headers that remain.
Assign a default type (e.g., "string") to any newly added headers that do not have an existing type.
This ensures that both adding and deleting columns are handled gracefully, maintaining the integrity of the headers and their associated types.
Implementation
Here's how you can modify Code 2 to address the issue:
Update the on_columns_deleted Method:
Replace the existing on_columns_deleted method with the following implementation. This version ensures that new headers are assigned a default type while preserving the types of existing headers.
def on_columns_deleted(self, event):
"""Handle column deletion and update filter headers."""
if not self.current_table_name or not self.current_sheet:
return
new_headers = self.current_sheet.headers()
old_headers = self.headers[self.current_table_name]
# Create a mapping from old header names to their types
old_header_map = {col['name']: col['type'] for col in old_headers}
# Reconstruct headers with existing types or assign default 'string' type
updated_headers = []
for h in new_headers:
if h in old_header_map:
updated_headers.append({'name': h, 'type': old_header_map[h]})
else:
# Assign default type for new columns
updated_headers.append({'name': h, 'type': 'string'})
self.headers[self.current_table_name] = updated_headers
self.filter_header_dropdown['values'] = ["All"] + [col['name'] for col in updated_headers]
self.filter_header_var.set("All")
self.filter_option_var.set("contains")
self.filter_text_var.set("")
self.filter_text_entry.config(state='normal')
self.apply_filter()
self.save_data()
Ensure Default Types for New Columns:
When new columns are added (not through deletion but by the user interacting with the tksheet widget), ensure that they are assigned a default type. Modify the method that handles column additions if necessary. If column additions are implicitly handled by tksheet, the above modification to on_columns_deleted will cover assigning default types to any new headers that emerge post addition.
Verify Other Header-Related Methods:
Ensure that all other methods interacting with headers account for the type field. For instance:
Adding New Tables:
When adding a new table, initialize headers with both name and type.
def add_table(self, table_name: str, data: list[list[str]] | None = None, headers: Optional[list[dict[str, str]]] = None):
"""Add a new table."""
if headers:
self.headers[table_name] = headers
else:
default_headers = [
{"name": "Column 1", "type": "string"},
{"name": "Column 2", "type": "string"},
{"name": "Column 3", "type": "string"},
{"name": "Column 4", "type": "string"},
{"name": "Column 5", "type": "string"}
]
self.headers[table_name] = default_headers
self.tables_data[table_name] = {"headers": self.headers[table_name], "data": data or [["" for _ in range(len(self.headers[table_name]))] for _ in range(10)]}
self.create_table_label(table_name)
self.save_data()
Loading Tables:
When loading tables from a file, ensure that headers are correctly reconstructed with both name and type. If legacy data lacks types, assign a default type.
def load_tables(self):
"""Load tables from file."""
if not self.save_file_path.exists():
return
try:
with self.save_file_path.open('r', encoding='utf-8') as file:
all_data = json.load(file)
except Exception as e:
messagebox.showerror("Load Error", f"Failed to load tables: {e}")
return
for table_name, data in all_data.items():
if not isinstance(data, list) or not data:
continue
headers, table_data = data[0], data[1:]
if all(isinstance(col, dict) and 'name' in col and 'type' in col for col in headers):
self.headers[table_name] = headers
else:
# Legacy support: Convert list of header names to dict with type 'string'
self.headers[table_name] = [{"name": h, "type": "string"} for h in headers]
self.tables_data[table_name] = {"headers": self.headers[table_name], "data": table_data}
self.create_table_label(table_name)
self.sort_table_labels()
Exporting Tables:
When exporting tables, ensure that headers retain their name and type information if exporting to a format that supports it (like JSON). For CSV exports, only the name is relevant.
def export_table(self):
"""Export current table to file."""
if not self.current_table_name or self.current_table_name not in self.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.current_table_name)
if not file_path:
return
try:
if file_path.endswith('.csv'):
# Extract header names
headers = [col['name'] for col in self.headers[self.current_table_name]]
# Convert all data to strings
data = [headers] + [[str(cell) for cell in row] for row in self.tables_data[self.current_table_name]["data"]]
self.save_table_data(file_path, data, 'csv')
elif file_path.endswith('.json'):
# Prepare data with headers (including types)
headers = self.headers[self.current_table_name]
data = [headers] + self.tables_data[self.current_table_name]["data"]
with open(file_path, 'w', encoding='utf-8') as file:
json.dump(data, file, indent=4)
else:
raise ValueError("Unsupported file format.")
self.save_data()
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}")
Testing the Changes:
After implementing the above changes, thoroughly test the application to ensure that:
Adding Columns: When a new column is added via the tksheet interface, it appears in the filter dropdown with the default type ("string").
Deleting Columns: When a column is deleted, it is removed from both the tksheet interface and the internal headers structure without affecting other columns.
Filtering: Filters continue to work correctly based on the updated headers.
Renaming Headers: Renaming headers maintains the association with their data types.
Final Corrected on_columns_deleted Method
Here's the complete corrected on_columns_deleted method for Code 2:
def on_columns_deleted(self, event):
"""Handle column deletion and update filter headers."""
if not self.current_table_name or not self.current_sheet:
return
new_headers = self.current_sheet.headers()
old_headers = self.headers[self.current_table_name]
# Create a mapping from old header names to their types
old_header_map = {col['name']: col['type'] for col in old_headers}
# Reconstruct headers with existing types or assign default 'string' type
updated_headers = []
for h in new_headers:
if h in old_header_map:
updated_headers.append({'name': h, 'type': old_header_map[h]})
else:
# Assign default type for new columns
updated_headers.append({'name': h, 'type': 'string'})
self.headers[self.current_table_name] = updated_headers
self.filter_header_dropdown['values'] = ["All"] + [col['name'] for col in updated_headers]
self.filter_header_var.set("All")
self.filter_option_var.set("contains")
self.filter_text_var.set("")
self.filter_text_entry.config(state='normal')
self.apply_filter()
self.save_data()
Summary
By ensuring that Code 2 correctly handles both the names and types of headers during column additions and deletions, you can achieve the same robust functionality as observed in Code 1. The key is to manage the additional complexity introduced by the type field without disrupting the synchronization between the GUI (tksheet) and the internal data structures.