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")
To make the handling of the update_true_counter function more efficient and to correctly display boolean counts in the header, we need to implement the method in the class and ensure that it updates a label in the header UI. Additionally, we need to modify the method of the class to include this label.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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."""
2. Implement the update_true_counter method in the Header class to update the label with the boolean counts:
def update_true_counter(self, count_text: str) -> None:
"""Update the true counter label with the given count text."""
if self.true_counter_label:
self.true_counter_label.config(text=count_text)
With these changes, the Header class now correctly displays the counts of True values for boolean columns in the header UI. The update_true_counter method updates the true_counter_label whenever it's called, ensuring that the UI reflects the current state of the boolean counts.
Explanation:
In _setup_lower_section:
We create a tk.Label called true_counter_label and add it to self.lower_header_frame.
This label is initially empty but will display the counts once updated.
In update_true_counter:
We check if true_counter_label exists and then update its text property with the provided count_text.
This method is called from other parts of the application (e.g., when loading a table or after modifying data) to refresh the displayed counts.
By implementing these methods correctly, we ensure that the boolean counts are efficiently handled and displayed in the application's header section.