The update_true_counter function in the header class seems to be in the wrong position. Make the handeling of it to be more efficient. Print all the functions that need to be changed in full. Lets think step by step. Python Code: 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, Union
from tksheet import Sheet, int_formatter, float_formatter, bool_formatter, num2alpha
def set_dpi_awareness() -> None:
"""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 create_frame(parent: tk.Widget, width: Optional[int] = None, bg: str = "SystemButtonFace") -> tk.Frame:
"""Creates a frame with specified width and background color."""
return tk.Frame(parent, width=width, bg=bg, bd=0, relief="flat")
class DataManager:
"""Manages table data persistence operations."""
def __init__(self, app: 'TableApp') -> None:
"""Initialize data manager with app reference."""
self.app = app
self.save_file_path = Path(__file__).parent / "data.json"
self.tables_data: dict[str, dict[str, Any]] = {}
self.headers: dict[str, list[str]] = {}
def load_tables(self) -> None:
"""Load and process tables from JSON file."""
if not self._load_json_data():
return
for table_name, table_info in self._load_json_data().items():
self._process_table(table_name, table_info)
self.app.sidebar.sort_table_labels()
def _load_json_data(self) -> Optional[dict]:
"""Load JSON data from file, handling errors."""
if not self.save_file_path.exists():
return None
try:
return json.loads(self.save_file_path.read_text(encoding="utf-8"))
except Exception as e:
messagebox.showerror("Load Error", f"Failed to load tables: {e}")
return None
def _process_table(self, table_name: str, table_info: dict) -> None:
"""Process individual table data and update internal storage."""
headers, table_data, data_types = self._parse_table_info(table_info)
if not headers or not table_data:
return
processed_data = self._convert_booleans(table_data, data_types)
self.headers[table_name] = headers
self.tables_data[table_name] = {
"headers": headers,
"data": processed_data,
"data_types": data_types
}
self.app.sidebar.create_table_label(table_name)
def _parse_table_info(self, table_info: dict) -> tuple[list[str], list[list], list[str]]:
"""Parse table structure from JSON data."""
if isinstance(table_info, dict):
return (
table_info.get("headers", []),
table_info.get("data", []),
table_info.get("data_types", [])
)
if isinstance(table_info, list) and table_info:
headers = table_info[0]
return headers, table_info[1:], ["string"] * len(headers)
return [], [], []
def _convert_booleans(self, table_data: list[list], data_types: list[str]) -> list[list]:
"""Convert string boolean values to Python booleans."""
BOOLEAN_TRUE_VALUES = {"true", "1", "yes"}
if len(data_types) < len(table_data[0]) if table_data else 0:
data_types.extend(['string'] * (len(table_data[0]) - len(data_types)))
return [
[
str(value).lower() in BOOLEAN_TRUE_VALUES
if data_types[col_idx] == "boolean"
else value
for col_idx, value in enumerate(row)
]
for row in table_data
]
def save_data(self) -> None:
"""Save tables data to JSON file."""
all_data = {
name: {
"headers": info["headers"],
"data": info["data"],
"data_types": info.get("data_types", ["string"] * len(info["headers"]))
}
for name, info in self.tables_data.items()
}
try:
self.save_file_path.write_text(
json.dumps(all_data, indent=4),
encoding="utf-8"
)
except Exception as e:
print(f"Error saving data: {e}")
class TableOperationsManager:
"""Handles creating, deleting, renaming tables, and changing column data types."""
def __init__(self, app: 'TableApp'):
self.app = app
def create_new_table(self) -> None:
"""Create a new table with a unique name."""
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.table_display.load_selected_table(table_name)
def add_table(
self,
table_name: str,
data: Optional[list[list[str]]] = None,
headers: Optional[list[str]] = None,
data_types: Optional[list[str]] = None,
) -> None:
"""Add a new table with optional headers, data, and data types."""
headers = headers or ["Column 1", "Column 2", "Column 3", "Column 4", "Column 5"]
data_types = data_types or ['string'] * len(headers)
self.app.data_manager.headers[table_name] = headers
self.app.data_manager.tables_data[table_name] = {
"headers": headers,
"data": data or [[""] * len(headers) for _ in range(10)],
"data_types": data_types,
}
self.app.sidebar.create_table_label(table_name)
self.app.data_manager.save_data()
def delete_table(self) -> None:
"""Delete the currently selected table with user confirmation."""
table_name = self.app.current_table_name
if not table_name or table_name not in self.app.data_manager.tables_data:
messagebox.showwarning("No Table Selected", "Please select a valid table to delete.")
return
confirmed = messagebox.askyesno("Delete Table", f"Are you sure you want to delete the table '{table_name}'?")
if confirmed:
self.remove_table(table_name)
def remove_table(self, table_name: str) -> None:
"""Remove the specified table and associated resources."""
if table_name == self.app.current_table_name:
self.app.current_sheet.destroy()
self.app.current_sheet = None
label = self.app.sidebar.table_labels.pop(table_name, None)
if label:
label.destroy()
self.app.data_manager.tables_data.pop(table_name, None)
self.app.data_manager.headers.pop(table_name, None)
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 begin_rename(self, table_name: str) -> None:
"""Initiate renaming of the specified 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()
rename_entry = tk.Entry(
self.app.sidebar.table_labels_frame,
bg=label.cget("bg"),
fg=self.app.colors["text"],
relief="flat",
)
rename_entry.insert(0, table_name)
rename_entry.place(
x=label.winfo_x(),
y=label.winfo_y(),
width=label.winfo_width(),
height=label.winfo_height(),
)
rename_entry.focus()
rename_entry.select_range(0, tk.END)
rename_entry.bind("<Return>", lambda event: self.end_rename(table_name))
rename_entry.bind("<FocusOut>", lambda event: self.cancel_rename())
self.app.sidebar.rename_entry = rename_entry
def end_rename(self, old_name: str) -> None:
"""Finalize renaming of the specified table."""
new_name = self.app.sidebar.rename_entry.get().strip()
if not new_name:
messagebox.showerror("Invalid Name", "Table name cannot be empty.")
self.end_rename(old_name)
return
if new_name != old_name and new_name in self.app.data_manager.tables_data:
messagebox.showerror("Duplicate Name", f"A table named '{new_name}' already exists.")
self.end_rename(old_name)
return
if new_name != old_name:
self.update_table_name(old_name, new_name)
self.app.table_display.load_selected_table(new_name)
self.cancel_rename()
def update_table_name(self, old_name: str, new_name: str) -> None:
"""Update the name of the table and associated UI elements."""
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.table_display.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:
label.config(bg=self.app.colors.get("button_selected", "default_color"))
self.app.data_manager.save_data()
self.app.sidebar.sort_table_labels()
def cancel_rename(self) -> None:
"""Cancel the rename operation."""
if self.app.sidebar.rename_entry:
self.app.sidebar.rename_entry.destroy()
self.app.sidebar.rename_entry = None
def change_column_data_types(self) -> None:
"""Change the data types of columns in the currently selected table."""
table_name = self.app.current_table_name
if not table_name:
messagebox.showwarning("No Table Selected", "Please select a table to change datatypes.")
return
current_headers = self.app.current_sheet.headers() if self.app.current_sheet else []
self.app.data_manager.headers[table_name] = current_headers
data_types = self.app.data_manager.tables_data[table_name].get("data_types", [])
while len(data_types) < len(current_headers):
data_types.append('string')
dialog = Header(self.app.root, current_headers, data_types)
if dialog.result:
new_data_types = dialog.result
self.app.data_manager.tables_data[table_name]["data_types"] = new_data_types
self.app.data_manager.save_data()
self.app.table_display.apply_column_data_types(new_data_types)
self.app.table_display.process_and_save_current_sheet_data()
self.app.refresh_table()
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", [])
boolean_counts = {}
for col_idx, dtype in enumerate(data_types):
if dtype == "boolean":
true_count = sum(1 for row in data if row[col_idx] is True)
if true_count > 0:
boolean_counts[headers[col_idx]] = true_count
if boolean_counts:
count_text = " | ".join(f"{col}: {count}" for col, count in boolean_counts.items())
self.app.header.update_true_counter(count_text)
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 := table_info.get("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()
self.update_boolean_counts()
else:
print(f"Row index {row} out of range for displayed_row_indices")
def update_boolean_counts(self) -> None:
"""Calculate and update the boolean counts for the current table."""
if not self.app.current_table_name:
return
table_info = self.app.data_manager.tables_data[self.app.current_table_name]
headers = table_info["headers"]
data = table_info["data"]
data_types = table_info.get("data_types", [])
boolean_counts = {}
for col_idx, dtype in enumerate(data_types):
if dtype == "boolean":
true_count = sum(1 for row in data if row[col_idx] is True)
if true_count > 0:
boolean_counts[headers[col_idx]] = true_count
count_text = " | ".join(f"{col}: {count}" for col, count in boolean_counts.items()) if boolean_counts else ""
self.app.header.update_true_counter(count_text)
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
class TableIOManager:
"""Handles importing and exporting tables."""
def __init__(self, app: "TableApp"):
"""Initialize the TableIOManager with the provided TableApp instance."""
self.app = app
def _parse_header_with_type(self, header: str) -> tuple[str, str]:
"""Extract column name and data type from header format: 'Name (type)'."""
match = re.match(r'^(.*?)\s*\((string|float|boolean|integer)\)$', header)
if match:
return match.group(1), match.group(2)
return header, 'string'
def _format_header_with_type(self, header: str, data_type: str) -> str:
"""Format header with its data type: 'Name (type)'."""
return f"{header} ({data_type})"
def import_file(self):
"""Import table from file using a file dialog and appropriate readers."""
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:
headers, table_data, data_types = self._read_table_data(file_path)
self.add_table_from_data(file_path, headers, table_data, data_types)
except Exception as e:
messagebox.showerror("File Import Error", str(e))
def _read_table_data(self, file_path: str) -> tuple[list[str], list[list[Any]], list[str]]:
"""Read table data and data types from a file based on its extension."""
match Path(file_path).suffix.lower():
case ".csv":
with open(file_path, newline="", encoding="utf-8") as csvfile:
data = list(csv.reader(csvfile))
raw_headers, table_data = data[0], data[1:]
parsed_headers_and_types = [self._parse_header_with_type(h) for h in raw_headers]
headers = [h[0] for h in parsed_headers_and_types]
data_types = [h[1] for h in parsed_headers_and_types]
converted_data = []
for row in table_data:
converted_row = []
for value, dtype in zip(row, data_types):
try:
match dtype:
case 'integer':
converted_row.append(int(value) if value else '')
case 'float':
converted_row.append(float(value) if value else '')
case 'boolean':
converted_row.append(value.lower() == 'true' if value else '')
case _:
converted_row.append(value)
except (ValueError, TypeError):
converted_row.append('')
converted_data.append(converted_row)
return headers, converted_data, data_types
case ".json":
with open(file_path, "r", encoding="utf-8") as jsonfile:
json_data = json.load(jsonfile)
headers = json_data.get('headers', [])
table_data = json_data.get('data', [])
data_types = json_data.get('data_types', ['string'] * len(headers))
return headers, table_data, data_types
case _:
raise ValueError("Unsupported file format.")
def add_table_from_data(
self, file_path: str, headers: list[str], table_data: list[list[str]], data_types: list[str]
):
"""Add a table from file data by creating a unique name and loading it into the application."""
table_name = self.ensure_unique_table_name(Path(file_path).stem)
self.app.table_operations.add_table(table_name, data=table_data, headers=headers, data_types=data_types)
self.app.table_display.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 by appending a counter if necessary."""
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 the current table to a file using a file dialog and appropriate writers based on file extension."""
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._prepare_table_data_for_export()
self._write_table_data(file_path, data)
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 _prepare_table_data_for_export(self) -> list[list[Any]]:
"""Prepare table data for export, including headers and rows."""
return (
[self.app.data_manager.headers[self.app.current_table_name]]
+ self.app.data_manager.tables_data[self.app.current_table_name]["data"]
)
def _write_table_data(self, file_path: str, data: list[list[Any]]):
"""Write table data to a file in the specified format."""
headers = data[0]
table_data = data[1:]
data_types = self.app.data_manager.tables_data[self.app.current_table_name].get("data_types", ['string'] * len(headers))
match Path(file_path).suffix.lower():
case ".csv":
self.save_table_data(file_path, data, "csv")
case ".json":
json_data = {
'headers': headers,
'data': table_data,
'data_types': data_types
}
with open(file_path, "w", encoding="utf-8") as file:
json.dump(json_data, file, indent=4)
case _:
raise ValueError("Unsupported file format.")
def save_table_data(self, file_path: str, data: list[list[Any]], file_format: str):
"""Save table data in a specified format (CSV or JSON)."""
if file_format == "csv":
headers = data[0]
data_rows = data[1:]
data_types = self.app.data_manager.tables_data[self.app.current_table_name].get("data_types", ['string'] * len(headers))
headers_with_types = [
self._format_header_with_type(header, dtype)
for header, dtype in zip(headers, data_types)
]
data_as_strings = [
[self._convert_cell_to_string(cell, data_types[idx]) for idx, cell in enumerate(row)]
for row in data_rows
]
with open(file_path, "w", newline="", encoding="utf-8") as file:
csv.writer(file).writerows([headers_with_types] + data_as_strings)
elif file_format == "json":
with open(file_path, "w", encoding="utf-8") as file:
json.dump(data, file, indent=4)
else:
raise ValueError("Unsupported file format.")
def _convert_cell_to_string(self, cell: Any, data_type: str) -> str:
"""Convert a cell to a string based on its data type."""
if cell is None:
return ''
try:
match data_type:
case "boolean":
if isinstance(cell, bool):
return str(cell).upper()
return str(cell.lower() == 'true').upper()
case "float":
if isinstance(cell, (int, float)):
return str(float(cell))
return str(float(cell.replace(',', ''))) if cell.strip() else ''
case "integer":
if isinstance(cell, (int, float)):
return str(int(cell))
return str(int(float(cell.replace(',', '')))) if cell.strip() else ''
case _:
return str(cell)
except (ValueError, AttributeError, TypeError):
return ''
class Sidebar:
"""Handles all sidebar-related UI and interactions."""
class Header:
"""Class for handling header UI."""
DATA_TYPE_OPTIONS = ["string", "integer", "float", "boolean"]
def __init__(self, root: tk.Tk, app: 'TableApp'):
self.root = root
self.app = app
self.style = app.style
self.colors = app.colors
self.fonts = app.fonts
self.dimensions = app.dimensions
self.table_name_label = None
self.lower_header_frame = None
self.result = None
self._setup_header()
def _setup_header(self) -> None:
header_frame = self._setup_main_frame()
self._setup_upper_section(header_frame)
self._setup_lower_section(header_frame)
def _setup_main_frame(self) -> tk.Frame:
header_frame = 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)
header_frame.grid_rowconfigure(0, weight=0)
header_frame.grid_rowconfigure(1, weight=0)
for i in range(5):
header_frame.grid_columnconfigure(i, weight=1 if i == 4 else 0)
return header_frame
def _setup_upper_section(self, parent: tk.Frame) -> None:
upper_frame = create_frame(parent=parent, width=None, bg=self.colors["background"])
upper_frame.grid(row=0, column=0, columnspan=6, sticky="ew", pady=(0, 10))
upper_frame.grid_columnconfigure(5, weight=1)
self._add_upper_content(upper_frame)
def _add_upper_content(self, frame: tk.Frame) -> None:
tk.Label(
frame, text="Data > ", bg=self.colors["background"], fg=self.colors["header_info"], font=self.fonts["header_info"]
).grid(row=0, column=0, padx=22, pady=(22, 0), sticky="nw")
self.table_name_label = tk.Label(
frame, text=self.app.current_table_name or "No Table Selected", bg=self.colors["background"], fg=self.colors["text"], font=self.fonts["header_info"]
)
self.table_name_label.grid(row=0, column=0, padx=(88, 10), pady=(22, 0), sticky="nw")
self._setup_settings_section(frame)
def _setup_settings_section(self, frame: tk.Frame) -> None:
settings_container = tk.Frame(frame, bg=self.colors["background"])
settings_container.grid(row=0, column=5, padx=(0, 40), pady=(22, 0), sticky="ne")
common_label_options = {
'bg': self.colors["background"],
'fg': self.colors["text"],
'font': self.fonts["text"],
'cursor': "hand2",
'width': 2,
'height': 1
}
buttons_frame = tk.Frame(settings_container, bg=self.colors["background"])
buttons_frame.pack(side=tk.LEFT)
labels = ['S', 'I', 'E', 'D']
actions = [self.show_stats, self.app.table_io.import_file, self.app.table_io.export_table, self.show_datatype_dialog]
for label_text, action in zip(labels, actions):
label = tk.Label(buttons_frame, text=label_text, **common_label_options)
label.pack(side=tk.LEFT)
label.bind("<Button-1>", lambda e, act=action: act())
label.bind("<Enter>", lambda e, lbl=label: lbl.config(bg=self.colors["button_selected"]))
label.bind("<Leave>", lambda e, lbl=label: lbl.config(bg=self.colors["background"]))
def _setup_lower_section(self, parent: tk.Frame) -> None:
self.lower_header_frame = create_frame(parent=parent, width=None, bg=self.colors["background"])
self.lower_header_frame.grid(row=1, column=0, columnspan=5, sticky="ew")
def show_stats(self):
"""Display stats about the boolean columns in a menu-like popup with a table."""
table_name = self.app.current_table_name
if not table_name:
messagebox.showwarning("No Table Selected", "Please select a table to view stats.")
return
if not self.app.current_sheet:
messagebox.showwarning("No Data", "No data available to show stats.")
return
data = self.app.current_sheet.get_sheet_data()
current_headers = self.app.current_sheet.headers()
data_types = self.app.data_manager.tables_data[table_name].get("data_types", [])
while len(data_types) < len(current_headers):
data_types.append('string')
total_rows = len(data)
boolean_columns = []
for col_idx, dtype in enumerate(data_types):
if dtype == 'boolean':
header = current_headers[col_idx]
column_data = [bool(row[col_idx]) if row[col_idx] is not None else False for row in data]
true_count = sum(1 for val in column_data if val is True)
false_count = sum(1 for val in column_data if val is False)
boolean_columns.append((header, true_count, false_count))
if hasattr(self, 'stats_popup') and self.stats_popup.winfo_exists():
self.stats_popup.destroy()
self.stats_popup = tk.Toplevel(self.root)
self.stats_popup.overrideredirect(True)
border_frame = tk.Frame(self.stats_popup, bg=self.colors["frame_border"])
border_frame.pack(padx=0, pady=0, expand=True, fill=tk.BOTH)
content_frame = tk.Frame(border_frame, bg=self.colors["background"])
content_frame.pack(padx=1, pady=1, expand=True, fill=tk.BOTH)
inner_frame = tk.Frame(content_frame, bg=self.colors["background"])
inner_frame.pack(padx=10, pady=10, expand=True, fill=tk.BOTH)
total_label = tk.Label(
inner_frame, text=f"Number of Rows: {total_rows}", bg=self.colors["background"], fg=self.colors["text"], font=self.fonts["menu"]
)
total_label.pack(pady=(0, 5), anchor='center')
separator = tk.Frame(inner_frame, bg=self.colors["separator_menu"], height=1)
separator.pack(fill=tk.X, pady=(0, 5))
if boolean_columns:
table_frame = tk.Frame(inner_frame, bg=self.colors["background"])
table_frame.pack()
headers = ["Column", "True", "False"]
for col_num, header_text in enumerate(headers):
header_label = tk.Label(
table_frame, text=header_text, bg=self.colors["background"], fg=self.colors["text"], font=self.fonts["menu"]
)
header_label.grid(row=0, column=col_num, padx=10, pady=2, sticky='w')
for row_num, (header, true_count, false_count) in enumerate(boolean_columns, start=1):
header_label = tk.Label(
table_frame, text=header, bg=self.colors["background"], fg=self.colors["header_info"], font=self.fonts["menu"]
)
header_label.grid(row=row_num, column=0, padx=10, pady=2, sticky='w')
true_label = tk.Label(
table_frame, text=str(true_count), bg=self.colors["background"], fg=self.colors["header_info"], font=self.fonts["menu"]
)
true_label.grid(row=row_num, column=1, padx=10, pady=2, sticky='w')
false_label = tk.Label(
table_frame, text=str(false_count), bg=self.colors["background"], fg=self.colors["header_info"], font=self.fonts["menu"]
)
false_label.grid(row=row_num, column=2, padx=10, pady=2, sticky='w')
for col_num in range(3):
table_frame.grid_columnconfigure(col_num, weight=1)
else:
no_data_label = tk.Label(
inner_frame, text="No boolean columns to display.", bg=self.colors["background"], fg=self.colors["text"], font=self.fonts["menu"]
)
no_data_label.pack(pady=10)
self.stats_popup.update_idletasks()
popup_width = self.stats_popup.winfo_width()
popup_height = self.stats_popup.winfo_height()
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
menu_x = self.root.winfo_pointerx()
menu_y = self.root.winfo_pointery()
padding = 10
if menu_x + popup_width > screen_width - padding:
menu_x = screen_width - popup_width - padding
if menu_y + popup_height > screen_height - padding:
menu_y = screen_height - popup_height - padding
menu_x = max(padding, menu_x)
menu_y = max(padding, menu_y)
self.stats_popup.geometry(f"+{menu_x}+{menu_y}")
def close_popup(event=None):
if self.stats_popup.winfo_exists():
self.stats_popup.destroy()
self.root.unbind("<Button-1>", self.click_outside_popup)
self.root.unbind("<Configure>", self.window_resized)
def click_outside_popup(event):
if not str(event.widget).startswith(str(self.stats_popup)):
close_popup()
self.click_outside_popup = self.root.bind("<Button-1>", click_outside_popup)
self.window_resized = self.root.bind("<Configure>", lambda e: close_popup())
self.stats_popup.bind("<FocusOut>", close_popup)
self.stats_popup.bind("<Escape>", close_popup)
self.stats_popup.focus_force()
def update_true_counter(self, count_text: str) -> None:
pass
def show_datatype_dialog(self) -> None:
"""Show custom popup window for changing column data types."""
table_name = self.app.current_table_name
if not table_name:
messagebox.showwarning("No Table Selected", "Please select a table to change datatypes.")
return
current_headers = self.app.current_sheet.headers() if self.app.current_sheet else []
self.app.data_manager.headers[table_name] = current_headers
self.data_types = self.app.data_manager.tables_data[table_name].get("data_types", []).copy()
while len(self.data_types) < len(current_headers):
self.data_types.append('string')
if hasattr(self, 'datatype_popup') and self.datatype_popup.winfo_exists():
self.datatype_popup.destroy()
self.datatype_popup = tk.Toplevel(self.root)
self.datatype_popup.overrideredirect(True)
self.dropdown = None
border_frame = tk.Frame(self.datatype_popup, bg=self.colors["frame_border"])
border_frame.pack(padx=0, pady=0, expand=True, fill=tk.BOTH)
content_frame = tk.Frame(border_frame, bg=self.colors["background"])
content_frame.pack(padx=1, pady=1, expand=True, fill=tk.BOTH)
inner_frame = tk.Frame(content_frame, bg=self.colors["background"])
inner_frame.pack(padx=10, pady=10, expand=True, fill=tk.BOTH)
self.datatype_vars = {}
for header_index, header in enumerate(current_headers):
current_type = self.data_types[header_index]
frame = tk.Frame(inner_frame, bg=self.colors["background"])
frame.pack(fill=tk.X, pady=0)
header_label = tk.Label(
frame, text=f"{header}:", bg=self.colors["background"], fg=self.colors["text"], font=self.fonts["menu"]
)
header_label.pack(side=tk.LEFT, padx=(0, 10))
var = tk.StringVar(value=current_type)
dropdown_button = tk.Label(
frame, textvariable=var, bg=self.colors["background"], fg=self.colors["header_info"], font=self.fonts["menu"], cursor="hand2", width=6, anchor='w'
)
dropdown_button.pack(side=tk.RIGHT)
def on_enter(e, btn=dropdown_button):
btn.config(bg=self.colors["button_selected"])
def on_leave(e, btn=dropdown_button):
btn.config(bg=self.colors["background"])
dropdown_button.bind("<Enter>", on_enter)
dropdown_button.bind("<Leave>", on_leave)
def create_dropdown(header, var, button):
def show_dropdown(event):
if self.dropdown is not None and self.dropdown.winfo_exists():
self.dropdown.destroy()
self.dropdown = None
x = button.winfo_rootx()
y = button.winfo_rooty() + button.winfo_height()
dropdown = tk.Toplevel(self.datatype_popup)
self.dropdown = dropdown
dropdown.overrideredirect(True)
dropdown.geometry(f"+{x}+{y}")
border_frame = tk.Frame(dropdown, bg=self.colors["frame_border"])
border_frame.pack(padx=0, pady=0, expand=True, fill=tk.BOTH)
inner_frame = tk.Frame(border_frame, bg=self.colors["background"])
inner_frame.pack(padx=1, pady=1, expand=True, fill=tk.BOTH)
for option in self.DATA_TYPE_OPTIONS:
option_label = tk.Label(
inner_frame, text=option, bg=self.colors["background"], fg=self.colors["header_info"], font=self.fonts["menu"], anchor='w', width=6
)
option_label.pack(fill=tk.X)
def on_enter(e, lbl=option_label):
lbl.config(bg=self.colors["button_selected"])
def on_leave(e, lbl=option_label):
lbl.config(bg=self.colors["background"])
option_label.bind("<Enter>", on_enter)
option_label.bind("<Leave>", on_leave)
def on_option_select(e, opt=option):
var.set(opt)
dropdown.destroy()
self.dropdown = None
return "break"
option_label.bind("<Button-1>", on_option_select)
dropdown.bind("<Button-1>", lambda e: "break")
dropdown.focus_force()
return "break"
button.bind("<Button-1>", show_dropdown)
button.bind("<Button-1>", lambda e: "break", add="+")
create_dropdown(header, var, dropdown_button)
self.datatype_vars[header] = var
separator = tk.Frame(inner_frame, bg=self.colors["separator_menu"], height=1)
separator.pack(fill=tk.X, pady=(5, 5))
apply_container = tk.Frame(
inner_frame, bg=self.colors["background"], cursor="hand2"
)
apply_container.pack(fill=tk.X, pady=(5, 0))
apply_label = tk.Label(
apply_container, text="Apply Changes", bg=self.colors["background"], fg=self.colors["text"], font=self.fonts["menu"], cursor="hand2"
)
apply_label.pack(expand=True, fill=tk.BOTH, pady=0)
def on_hover_enter(event):
apply_container.config(bg=self.colors["button_selected"])
apply_label.config(bg=self.colors["button_selected"])
def on_hover_leave(event):
apply_container.config(bg=self.colors["background"])
apply_label.config(bg=self.colors["background"])
apply_container.bind("<Enter>", on_hover_enter)
apply_container.bind("<Leave>", on_hover_leave)
apply_label.bind("<Enter>", on_hover_enter)
apply_label.bind("<Leave>", on_hover_leave)
apply_container.bind("<Button-1>", lambda e: self._apply_changes())
apply_label.bind("<Button-1>", lambda e: self._apply_changes())
self.datatype_popup.update_idletasks()
popup_width = self.datatype_popup.winfo_width()
popup_height = self.datatype_popup.winfo_height()
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
menu_x = self.root.winfo_pointerx()
menu_y = self.root.winfo_pointery()
padding = 10
if menu_x + popup_width > screen_width - padding:
menu_x = screen_width - popup_width - padding
if menu_y + popup_height > screen_height - padding:
menu_y = screen_height - popup_height - padding
menu_x = max(padding, menu_x)
menu_y = max(padding, menu_y)
self.datatype_popup.geometry(f"+{menu_x}+{menu_y}")
def is_descendant(widget, ancestor):
while widget:
if widget == ancestor:
return True
widget = widget.master
return False
def close_dropdown(event=None):
if self.dropdown is not None and self.dropdown.winfo_exists():
self.dropdown.destroy()
self.dropdown = None
def close_popup(event=None):
if self.datatype_popup.winfo_exists():
self.datatype_popup.destroy()
close_dropdown()
self.root.unbind("<Button-1>", self.click_outside_popup)
self.root.unbind("<Configure>", self.window_resized)
def click_outside_popup(event):
if not is_descendant(event.widget, self.datatype_popup):
close_popup()
def on_datatype_popup_click(event):
if self.dropdown is not None and self.dropdown.winfo_exists():
if not is_descendant(event.widget, self.dropdown):
close_dropdown()
return "break"
return None
self.datatype_popup.bind("<Button-1>", on_datatype_popup_click)
self.click_outside_popup = self.root.bind("<Button-1>", click_outside_popup)
self.window_resized = self.root.bind("<Configure>", lambda e: close_popup())
self.datatype_popup.bind("<Escape>", close_popup)
self.datatype_popup.focus_force()
def _apply_changes(self) -> None:
"""Apply the datatype changes and update the table."""
table_name = self.app.current_table_name
current_headers = self.app.current_sheet.headers() if self.app.current_sheet else []
self.data_types = []
for header in current_headers:
dtype = self.datatype_vars[header].get()
self.data_types.append(dtype)
self.app.data_manager.tables_data[table_name]["data_types"] = self.data_types
self.app.data_manager.save_data()
self.app.table_display.apply_column_data_types(self.data_types)
self.app.table_display.process_and_save_current_sheet_data()
self.app.refresh_table()
if hasattr(self, 'datatype_popup') and self.datatype_popup.winfo_exists():
self.datatype_popup.destroy()
class FilterControls:
"""Manages filtering logic and UI components."""
FILTER_OPTIONS: dict[str, callable] = {
"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 != "",
}
def __init__(self, parent: tk.Frame, app: 'TableApp'):
"""Initialize the filter controls with the parent frame and application."""
self.app = app
self.root = parent
self.colors = app.colors
self.fonts = app.fonts
self.style = app.style
self._setup_variables()
self.create_filter_controls()
def _setup_variables(self) -> None:
"""Setup tkinter variables used for filtering."""
self.filter_header_var = tk.StringVar(value="All")
self.filter_option_var = tk.StringVar(value="contains")
self.filter_text_var = tk.StringVar()
def create_filter_controls(self) -> None:
"""Create and configure filter controls."""
header_dropdown, option_dropdown, text_entry = self._create_filter_components()
self._configure_filter_components(header_dropdown, option_dropdown, text_entry)
self._bind_filter_events()
def _create_filter_components(self) -> tuple[tk.Frame, tk.Frame, tk.Frame]:
"""Create filter UI components."""
headers = self.app.data_manager.headers.get(self.app.current_table_name, ["All"])
filter_frame, header_dropdown, option_dropdown, text_entry = custom_filter_design(
self.root,
self.style,
headers=headers,
filter_types=list(self.FILTER_OPTIONS.keys()),
filter_font=self.fonts["filter"],
filter_combobox_font=self.fonts["filter_combobox"],
colors=self.colors,
)
filter_frame.grid(row=0, column=1, columnspan=4, padx=100, pady=0, sticky="ew")
return header_dropdown, option_dropdown, text_entry
def _configure_filter_components(self, header_dropdown: tk.Frame, option_dropdown: tk.Frame, text_entry: tk.Frame) -> None:
"""Configure filter components with variables and display settings."""
self.filter_header_dropdown = header_dropdown
self.filter_option_dropdown = option_dropdown
self.filter_text_entry = text_entry
self.filter_header_dropdown["textvariable"] = self.filter_header_var
self.filter_option_dropdown["textvariable"] = self.filter_option_var
self.filter_text_entry["textvariable"] = self.filter_text_var
def _bind_filter_events(self) -> None:
"""Bind events to filter components."""
self.filter_header_dropdown.bind("<<ComboboxSelected>>", self.apply_filter)
self.filter_option_dropdown.bind(
"<<ComboboxSelected>>",
lambda event: [self.update_filter_text_state(event), self.apply_filter()],
)
self.filter_text_entry.bind("<KeyRelease>", self.apply_filter)
self.filter_text_entry.bind("<Return>", self.apply_filter)
def update_filter_text_state(self, event=None) -> None:
"""Enable or disable the filter text entry based on filter option."""
option = self.filter_option_var.get()
is_special_option = option in ["is empty", "is not empty"]
self.filter_text_entry.config(state="disabled" if is_special_option else "normal")
if is_special_option:
self.filter_text_var.set("")
self.apply_filter()
def apply_filter(self, event=None) -> None:
"""Apply filter to table data based on selected criteria."""
if not self._is_filtering_possible():
return
displayed_indices = self._filter_data()
self._update_display(displayed_indices)
def _is_filtering_possible(self) -> bool:
"""Check if filtering is possible with the current application state."""
return bool(self.app.current_table_name and self.app.current_sheet)
def _filter_data(self) -> list[int]:
"""Filter data based on current filter settings."""
header = self.filter_header_var.get()
option = self.filter_option_var.get()
text = self.filter_text_var.get().lower()
original_data = self.app.data_manager.tables_data[self.app.current_table_name].get("data", [])
target_indices = self._get_target_indices(header)
filter_func = self.FILTER_OPTIONS[option]
displayed_indices = [
i
for i, row in enumerate(original_data)
if any(filter_func(str(row[idx]).lower(), text) for idx in target_indices)
]
return displayed_indices
def _get_target_indices(self, header: str) -> list[int]:
"""Return indices to filter on based on the selected header."""
headers = self.app.data_manager.headers[self.app.current_table_name]
if header == "All":
return list(range(len(headers)))
if header in headers:
return [headers.index(header)]
return []
def _update_display(self, displayed_indices: list[int]) -> None:
"""Update the display with filtered data and reset row indexing."""
try:
total_rows = len(self.app.current_sheet.get_sheet_data())
self.app.current_sheet.hide_rows(set(range(total_rows)), data_indexes=True)
self.app.current_sheet.display_rows(displayed_indices, all_displayed=False, data_indexes=True)
new_index_values = []
current_number = 1
for i in range(total_rows):
if i in displayed_indices:
new_index_values.append(str(current_number))
current_number += 1
else:
new_index_values.append("")
self.app.current_sheet.set_index_data(new_index_values, redraw=True)
self.app.displayed_row_indices = displayed_indices
except tk.TclError as e:
print(f"Error applying filter: {e}")
def reset_row_indices(self) -> None:
"""Restore original row indices when clearing filters."""
if self.app.current_sheet:
total_rows = len(self.app.current_sheet.get_sheet_data())
original_indices = [str(i + 1) for i in range(total_rows)]
self.app.current_sheet.set_index_data(original_indices, redraw=True)
if name == "main":
set_dpi_awareness()
root = tk.Tk()
app = TableApp(root)
root.mainloop()
Certainly! Let's address the issue step by step to ensure that the update_true_counter function is optimally positioned and efficiently handled within your application.
Issue Overview
Problem: The update_true_counter method in the Header class is currently a placeholder (pass) and might not be efficiently positioned or utilized within the overall architecture.
Objective: Implement update_true_counter properly within the Header class and ensure that all related functions interact with it efficiently. We'll also ensure that unnecessary recalculations or UI updates are minimized.
Step-by-Step Solution
Implement update_true_counter in the Header Class:
Add a Label for Displaying Counts: We'll introduce a tk.Label within the Header class to display the boolean counts.
Update the update_true_counter Method: This method will now update the text of the newly added label.
Ensure Efficient Interaction Between Classes:
TableDisplayManager: Ensure that load_selected_table and update_boolean_counts correctly calculate and pass the count text to update_true_counter.
Avoid Redundant Calculations: Ensure that boolean counts are only recalculated when necessary to enhance efficiency.
Modify the UI Layout if Necessary:
Positioning the Counter: Ensure that the counter label is appropriately placed within the header for visibility and aesthetic purposes.
Updated Functions
Below are the full implementations of the functions that need to be changed or added to address the issues effectively.
1. Header Class Modifications
a. Add a Label for Boolean Counts in the Header
We'll modify the _add_upper_content method to include a label that will display the boolean counts.
class Header:
"""Class for handling header UI."""
DATA_TYPE_OPTIONS = ["string", "integer", "float", "boolean"]
def __init__(self, root: tk.Tk, app: 'TableApp'):
self.root = root
self.app = app
self.style = app.style
self.colors = app.colors
self.fonts = app.fonts
self.dimensions = app.dimensions
self.table_name_label = None
self.lower_header_frame = None
self.boolean_count_label = None # New label for boolean counts
self.result = None
self._setup_header()
def _setup_header(self) -> None:
header_frame = self._setup_main_frame()
self._setup_upper_section(header_frame)
self._setup_lower_section(header_frame)
def _setup_main_frame(self) -> tk.Frame:
header_frame = 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)
header_frame.grid_rowconfigure(0, weight=0)
header_frame.grid_rowconfigure(1, weight=0)
for i in range(5):
header_frame.grid_columnconfigure(i, weight=1 if i == 4 else 0)
return header_frame
def _setup_upper_section(self, parent: tk.Frame) -> None:
upper_frame = create_frame(parent=parent, width=None, bg=self.colors["background"])
upper_frame.grid(row=0, column=0, columnspan=6, sticky="ew", pady=(0, 10))
upper_frame.grid_columnconfigure(5, weight=1)
self._add_upper_content(upper_frame)
def _add_upper_content(self, frame: tk.Frame) -> None:
tk.Label(
frame, text="Data > ", bg=self.colors["background"], fg=self.colors["header_info"], font=self.fonts["header_info"]
).grid(row=0, column=0, padx=22, pady=(22, 0), sticky="nw")
self.table_name_label = tk.Label(
frame, text=self.app.current_table_name or "No Table Selected", bg=self.colors["background"], fg=self.colors["text"], font=self.fonts["header_info"]
)
self.table_name_label.grid(row=0, column=0, padx=(88, 10), pady=(22, 0), sticky="nw")
# Add Boolean Counts Label
self.boolean_count_label = tk.Label(
frame, text="", bg=self.colors["background"], fg=self.colors["text"], font=self.fonts["header_info"]
)
self.boolean_count_label.grid(row=1, column=0, padx=(88, 10), pady=(5, 0), sticky="nw")
self._setup_settings_section(frame)
def _setup_settings_section(self, frame: tk.Frame) -> None:
settings_container = tk.Frame(frame, bg=self.colors["background"])
settings_container.grid(row=0, column=5, padx=(0, 40), pady=(22, 0), sticky="ne")
common_label_options = {
'bg': self.colors["background"],
'fg': self.colors["text"],
'font': self.fonts["text"],
'cursor': "hand2",
'width': 2,
'height': 1
}
buttons_frame = tk.Frame(settings_container, bg=self.colors["background"])
buttons_frame.pack(side=tk.LEFT)
labels = ['S', 'I', 'E', 'D']
actions = [self.show_stats, self.app.table_io.import_file, self.app.table_io.export_table, self.show_datatype_dialog]
for label_text, action in zip(labels, actions):
label = tk.Label(buttons_frame, text=label_text, **common_label_options)
label.pack(side=tk.LEFT)
label.bind("<Button-1>", lambda e, act=action: act())
label.bind("<Enter>", lambda e, lbl=label: lbl.config(bg=self.colors["button_selected"]))
label.bind("<Leave>", lambda e, lbl=label: lbl.config(bg=self.colors["background"]))
def _setup_lower_section(self, parent: tk.Frame) -> None:
self.lower_header_frame = create_frame(parent=parent, width=None, bg=self.colors["background"])
self.lower_header_frame.grid(row=1, column=0, columnspan=5, sticky="ew")
def show_stats(self):
"""Display stats about the boolean columns in a menu-like popup with a table."""
table_name = self.app.current_table_name
if not table_name:
messagebox.showwarning("No Table Selected", "Please select a table to view stats.")
return
if not self.app.current_sheet:
messagebox.showwarning("No Data", "No data available to show stats.")
return
data = self.app.current_sheet.get_sheet_data()
current_headers = self.app.current_sheet.headers()
data_types = self.app.data_manager.tables_data[table_name].get("data_types", [])
while len(data_types) < len(current_headers):
data_types.append('string')
total_rows = len(data)
boolean_columns = []
for col_idx, dtype in enumerate(data_types):
if dtype == 'boolean':
header = current_headers[col_idx]
column_data = [bool(row[col_idx]) if row[col_idx] is not None else False for row in data]
true_count = sum(1 for val in column_data if val is True)
false_count = sum(1 for val in column_data if val is False)
boolean_columns.append((header, true_count, false_count))
if hasattr(self, 'stats_popup') and self.stats_popup.winfo_exists():
self.stats_popup.destroy()
self.stats_popup = tk.Toplevel(self.root)
self.stats_popup.overrideredirect(True)
border_frame = tk.Frame(self.stats_popup, bg=self.colors["frame_border"])
border_frame.pack(padx=0, pady=0, expand=True, fill=tk.BOTH)
content_frame = tk.Frame(border_frame, bg=self.colors["background"])
content_frame.pack(padx=1, pady=1, expand=True, fill=tk.BOTH)
inner_frame = tk.Frame(content_frame, bg=self.colors["background"])
inner_frame.pack(padx=10, pady=10, expand=True, fill=tk.BOTH)
total_label = tk.Label(
inner_frame, text=f"Number of Rows: {total_rows}", bg=self.colors["background"], fg=self.colors["text"], font=self.fonts["menu"]
)
total_label.pack(pady=(0, 5), anchor='center')
separator = tk.Frame(inner_frame, bg=self.colors["separator_menu"], height=1)
separator.pack(fill=tk.X, pady=(0, 5))
if boolean_columns:
table_frame = tk.Frame(inner_frame, bg=self.colors["background"])
table_frame.pack()
headers = ["Column", "True", "False"]
for col_num, header_text in enumerate(headers):
header_label = tk.Label(
table_frame, text=header_text, bg=self.colors["background"], fg=self.colors["text"], font=self.fonts["menu"]
)
header_label.grid(row=0, column=col_num, padx=10, pady=2, sticky='w')
for row_num, (header, true_count, false_count) in enumerate(boolean_columns, start=1):
header_label = tk.Label(
table_frame, text=header, bg=self.colors["background"], fg=self.colors["header_info"], font=self.fonts["menu"]
)
header_label.grid(row=row_num, column=0, padx=10, pady=2, sticky='w')
true_label = tk.Label(
table_frame, text=str(true_count), bg=self.colors["background"], fg=self.colors["header_info"], font=self.fonts["menu"]
)
true_label.grid(row=row_num, column=1, padx=10, pady=2, sticky='w')
false_label = tk.Label(
table_frame, text=str(false_count), bg=self.colors["background"], fg=self.colors["header_info"], font=self.fonts["menu"]
)
false_label.grid(row=row_num, column=2, padx=10, pady=2, sticky='w')
for col_num in range(3):
table_frame.grid_columnconfigure(col_num, weight=1)
else:
no_data_label = tk.Label(
inner_frame, text="No boolean columns to display.", bg=self.colors["background"], fg=self.colors["text"], font=self.fonts["menu"]
)
no_data_label.pack(pady=10)
self.stats_popup.update_idletasks()
popup_width = self.stats_popup.winfo_width()
popup_height = self.stats_popup.winfo_height()
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
menu_x = self.root.winfo_pointerx()
menu_y = self.root.winfo_pointery()
padding = 10
if menu_x + popup_width > screen_width - padding:
menu_x = screen_width - popup_width - padding
if menu_y + popup_height > screen_height - padding:
menu_y = screen_height - popup_height - padding
menu_x = max(padding, menu_x)
menu_y = max(padding, menu_y)
self.stats_popup.geometry(f"+{menu_x}+{menu_y}")
def close_popup(event=None):
if self.stats_popup.winfo_exists():
self.stats_popup.destroy()
self.root.unbind("<Button-1>", self.click_outside_popup)
self.root.unbind("<Configure>", self.window_resized)
def click_outside_popup(event):
if not str(event.widget).startswith(str(self.stats_popup)):
close_popup()
self.click_outside_popup = self.root.bind("<Button-1>", click_outside_popup)
self.window_resized = self.root.bind("<Configure>", lambda e: close_popup())
self.stats_popup.bind("<FocusOut>", close_popup)
self.stats_popup.bind("<Escape>", close_popup)
self.stats_popup.focus_force()
def update_true_counter(self, count_text: str) -> None:
"""Update the boolean counts label in the header."""
if self.boolean_count_label:
self.boolean_count_label.config(text=count_text)
Explanation of Changes:
Added boolean_count_label: A new tk.Label (self.boolean_count_label) is introduced in the Header class to display the boolean counts.
Positioning the Label: The boolean_count_label is positioned below the table name label for clear visibility.
Implemented update_true_counter: This method now updates the text attribute of boolean_count_label to reflect the current counts.
2. TableDisplayManager Class Modifications
Ensure that TableDisplayManager appropriately calculates and passes the count text to the Header class.
a. load_selected_table Method
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", [])
# Calculate boolean counts
boolean_counts = {}
for col_idx, dtype in enumerate(data_types):
if dtype == "boolean":
true_count = sum(1 for row in data if row[col_idx] is True)
if true_count > 0:
boolean_counts[headers[col_idx]] = true_count
# Update the Header with boolean counts
if boolean_counts:
count_text = " | ".join(f"{col}: {count}" for col, count in boolean_counts.items())
else:
count_text = ""
self.app.header.update_true_counter(count_text)
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 := table_info.get("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()
# ... [Rest of the TableDisplayManager methods remain unchanged]
b. update_boolean_counts Method
def update_boolean_counts(self) -> None:
"""Calculate and update the boolean counts for the current table."""
"""Handles only boolean counts and utilizes update_true_counter efficiently."""
if not self.app.current_table_name:
return
table_info = self.app.data_manager.tables_data[self.app.current_table_name]
headers = table_info["headers"]
data = table_info["data"]
data_types = table_info.get("data_types", [])
boolean_counts = {}
for col_idx, dtype in enumerate(data_types):
if dtype == "boolean":
true_count = sum(1 for row in data if row[col_idx] is True)
if true_count > 0:
boolean_counts[headers[col_idx]] = true_count
# Create a concise count_text string
count_text = " | ".join(f"{col}: {count}" for col, count in boolean_counts.items()) if boolean_counts else ""
# Update the Header with the new counts
self.app.header.update_true_counter(count_text)
Explanation of Changes:
Implemented update_true_counter: In the Header class, this method now updates the boolean_count_label with the provided count_text.
Added boolean_count_label: A label is added below the table name to display the boolean counts, enhancing visibility.
Modified load_selected_table: The method now calculates boolean_counts and constructs count_text accordingly, then calls update_true_counter with this text.
Optimized update_boolean_counts: This method now solely focuses on calculating boolean counts and updating the header without additional responsibilities, promoting single responsibility principle.
3. Other Considerations
a. Ensuring the Header Label Updates on Data Changes
If there are other places where data changes can affect the boolean counts (like cell edits), ensure that after such operations, update_boolean_counts is called. This ensures that the boolean_count_label remains accurate.
b. Debouncing Rapid Updates (Optional)
For enhanced efficiency, especially with large datasets or rapid successive changes, consider implementing a debounce mechanism to prevent excessive UI updates. This can be achieved using threading or by scheduling updates after brief intervals.
Final Thoughts
By implementing the update_true_counter method within the Header class and ensuring that it's efficiently called from the TableDisplayManager, we've streamlined the process of updating boolean counts in the UI. This approach adheres to good software design principles, ensuring that each class has a clear and single responsibility.
Feel free to integrate these changes into your application. If you encounter any further issues or need additional optimizations, don't hesitate to ask!