SYSTEM: You are a Python 3.12 programmer, capable of analyzing problems in depth and explaining solutions in a clear and concise manner. Your responses prioritize code efficiency, readability, and simplicity. You leverage the latest Python features. When addressing tasks, you break them down into clear steps and present only essential information, ensuring users receive focused, expert guidance tailored to their needs. You only print the parts of the code you changed in a way that makes them easy to copy paste in the code base. USER: Implement check boxes for boolean values (Yes/No). Use the tkinter handbook for guidance. tkinter Handbook: Data Formatting
By default tksheet stores all user inputted data as strings and while tksheet can store and display any datatype with a str() method this has some obvious limitations.
Data formatting aims to provide greater functionality when working with different datatypes and provide strict typing for the sheet. With formatting you can convert sheet data and user input to a specific datatype.
Additionally, formatting also provides a function for displaying data on the table GUI (as a rounded float for example) and logic for handling invalid and missing data.
tksheet has several basic built-in formatters and provides functionality for creating your own custom formats as well.
A demonstration of all the built-in and custom formatters can be found here.
Creation and deletion of data formatting rules
Creating a data format rule
Span objects (more information here) can be used to format data for cells, rows, columns and the entire sheet.
You can use either of the following methods:
Using a span method e.g. span.format() more information here.
Using a sheet method e.g. sheet.format(Span)
Or if you need user inserted row/columns in the middle of areas with data formatting to also be formatted you can use named spans, more information here.
Whether data is formatted for cells, rows or columns depends on the kind of span.
When applying multiple overlapping formats with e.g. a formatted cell which overlaps a formatted row, the priority is as follows:
Cell formats first.
Row formats second.
Column formats third.
Data formatting will effectively override validate_input = True on cells with dropdown boxes.
When getting data take careful note of the get_displayed options, as these are the difference between getting the actual formatted data and what is simply displayed on the table GUI.
Parameters:
key (CreateSpanTypes) either a span or a type which can create a span. See here for more information on the types that can create a span.
formatter_options (dict) a dictionary of keyword options/arguements to pass to the formatter, see here for information on what argument to use.
formatter_class (class) in case you want to use a custom class to store functions and information as opposed to using the built-in methods.
**kwargs any additional keyword options/arguements to pass to the formatter.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
key (CreateSpanTypes) either a span or a type which can create a span. See here for more information on the types that can create a span.
clear_values (bool) if true, all the cells covered by the span will have their values cleared.
clear_values (bool) if true, all the sheets cell values will be cleared.
Reapply formatting to entire sheet
reapply_formatting() -> Sheet
Useful if you have manually changed the entire sheets data using sheet.MT.data = and want to reformat the sheet using any existing formatting you have set.
Check if a cell is formatted
formatted(r: int, c: int) -> dict
If the cell is formatted function returns a dict with all the format keyword arguments. The dict will be empty if the cell is not formatted.
Formatters
In addition to the generic formatter, tksheet provides formatters for many different data types.
A basic example showing how formatting some columns as float might be done:
import tkinter as tk
from tksheet import (
Sheet,
float_formatter,
)
from tksheet import (
num2alpha,
)
class demo(tk.Tk):
def init(self):
super().init()
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=1)
self.sheet = Sheet(
self,
data=[[f"{r}", f"{r}"] for r in range(5)],
expand_sheet_if_paste_too_big=True,
theme="dark blue",
)
"""
Format example
"""
some keyword arguments inside float_formatter()
self.sheet.format(
num2alpha(0), # column A
formatter_options=float_formatter(
decimals=1,
nullable=True,
),
)
format_function (function) a function that takes a string and returns an int. By default, this is set to the in-built tksheet.to_int. This function will always convert float-likes to its floor, for example "5.9" will be converted to 5.
to_str_function (function) By default, this is set to the in-built tksheet.to_str, which is a very basic function that will displace the default string representation of the value.
The float_formatter is the basic configuration for a simple float formatter. It will always round float-likes to the specified number of decimal places, for example "5.999" will be converted to "6.0" if decimals = 1.
format_function (function) a function that takes a string and returns a float. By default, this is set to the in-built tksheet.to_float.
to_str_function (function) By default, this is set to the in-built tksheet.float_to_str, which will display the float to the specified number of decimal places.
decimals (int, None) the number of decimal places to round to. Defaults to 2.
Example:
sheet.format_cell(0, 0, formatter_options = tksheet.float_formatter(decimals = None)) # A float formatter with maximum float() decimal places
Percentage Formatter
The percentage_formatter is the basic configuration for a simple percentage formatter. It will always round float-likes as a percentage to the specified number of decimal places, for example "5.999%" will be converted to "6.0%" if decimals = 1.
format_function (function) a function that takes a string and returns a float. By default, this is set to the in-built tksheet.to_percentage. This function will always convert percentages to their decimal equivalent, for example "5%" will be converted to 0.05.
to_str_function (function) By default, this is set to the in-built tksheet.percentage_to_str, which will display the float as a percentage to the specified number of decimal places. For example, 0.05 will be displayed as "5.0%".
decimals (int) the number of decimal places to round to. Defaults to 0.
Example:
sheet.format_cell(0, 0, formatter_options=tksheet.percentage_formatter(decimals=1)) # A percentage formatter with 1 decimal place
Note:
By default percentage_formatter() converts user entry 21 to 2100% and 21% to 21%. An example where 21 is converted to 21% instead is shown below:
formats column A as percentage
uses:
format_function=alt_to_percentage
to_str_function=alt_percentage_to_str
format_function (function) a function that takes a string and returns a bool. By default, this is set to the in-built tksheet.to_bool.
to_str_function (function) By default, this is set to the in-built tksheet.bool_to_str, which will display the boolean as "True" or "False".
truthy (set) a set of values that will be converted to True. Defaults to the in-built tksheet.truthy.
falsy (set) a set of values that will be converted to False. Defaults to the in-built tksheet.falsy.
Example:
A bool formatter with custom truthy and falsy values to account for aussie and kiwi slang
This is the generic formatter options interface. You can use this to create your own custom formatters. The following options are available.
Note that all these options can also be passed to the Sheet() format functions as keyword arguments and are available as attributes for all formatters.
You can also provide functions of your own creation for all the below arguments which take functions if you require.
datatypes (list) a list of datatypes that the formatter will accept. For example, datatypes = [int, float] will accept integers and floats.
format_function (function) a function that takes a string and returns a value of the desired datatype. For example, format_function = int will convert a string to an integer.
to_str_function (function) a function that takes a value of the desired datatype and returns a string. This determines how the formatter displays its data on the table. For example, to_str_function = str will convert an integer to a string. Defaults to tksheet.to_str.
invalid_value (any) the value to return if the input string is invalid. For example, invalid_value = "NA" will return "NA" if the input string is invalid.
nullable (bool) if true, the formatter will accept None as a valid input.
pre_format_function (function) a function that takes a input string and returns a string. This function is called before the format_function and can be used to modify the input string before it is converted to the desired datatype. This can be useful if you want to strip out unwanted characters or convert a string to a different format before converting it to the desired datatype.
post_format_function (function) a function that takes a value which might not be of the desired datatype, e.g. None if the cell is nullable and empty and if successful returns a value of the desired datatype or if not successful returns the input value. This function is called after the format_function and can be used to modify the output value after it is converted to the desired datatype. This can be useful if you want to round a float for example.
clipboard_function (function) a function that takes a value of the desired datatype and returns a string. This function is called when the cell value is copied to the clipboard. This can be useful if you want to convert a value to a different format before it is copied to the clipboard.
**kwargs any additional keyword options/arguements to pass to the formatter. These keyword arguments will be passed to the format_function, to_str_function, and the clipboard_function. These can be useful if you want to specifiy any additional formatting options, such as the number of decimal places to round to.
Datetime Formatters and Designing Your Own Custom Formatters
tksheet is at the moment a dependency free library and so doesn't include a datetime parser as is.
You can however very easily make a datetime parser if you are willing to install a third-party package. Recommended are:
dateparser
dateutil
Both of these packages have a very comprehensive datetime parser which can be used to create a custom datetime formatter for tksheet.
Below is a simple example of how you might create a custom datetime formatter using the dateutil package.
from tksheet import *
from datetime import datetime, date
from dateutil.parser import parse
def to_local_datetime(dt, **kwargs):
'''
Our custom format_function, converts a string or a date to a datetime object in the local timezone.
'''
if isinstance(dt, datetime):
pass # Do nothing
elif isinstance(dt, date):
dt = datetime(dt.year, dt.month, dt.day) # Always good to account for unexpected inputs
else:
try:
dt = parser.parse(dt)
except:
raise ValueError(f"Could not parse {dt} as a datetime")
if dt.tzinfo is None:
dt = dt.replace(tzinfo = tzlocal()) # If no timezone is specified, assume local timezone
dt = dt.astimezone(tzlocal()) # Convert to local timezone
return dt
def datetime_to_str(dt, **kwargs):
'''
Our custom to_str_function, converts a datetime object to a string with a format that can be specfied in kwargs.
'''
return dt.strftime(kwargs['format'])
Now we can create our custom formatter dictionary from the generic formatter interface in tksheet
datetime_formatter = formatter(datatypes = datetime,
format_function = to_local_datetime,
to_str_function = datetime_to_str,
invalid_value = "NaT",
format = "%d/%m/%Y %H:%M:%S",
)
From here we can pass our datetime_formatter into sheet.format() or span.format() just like any other formatter
For those wanting even more customisation of their formatters you also have the option of creating a custom formatter class. This is a more advanced topic and is not covered here, but it's recommended to create a new class which is a subclass of the tksheet.Formatter class and overriding the methods you would like to customise. This custom class can then be passed into the format_cells() formatter_class argument.
Hiding Columns
Note that once you have hidden columns you can use the function displayed_column_to_data(column) to retrieve a column data index from a displayed index.
Display only certain columns
columns (int, iterable, "all") are the columns to be displayed, omit the columns to be hidden.
Use argument True with all_columns_displayed to display all columns, use False to display only the columns you've set using the columns arg.
You can also use the keyword argument all_displayed instead of all_columns_displayed.
Examples:
display all columns
self.sheet.display_columns("all")
displaying specific columns only
NOTE: columns (int) by default uses displayed column indexes, not data indexes. In other words the indexes of the columns displayed on the screen are the ones that are hidden, this is useful when used in conjunction with get_selected_columns().
data_indexes when False it makes the columns parameter indexes represent displayed columns and not the underlying Sheet data columns. When True the indexes represent data indexes.
Example:
columns_to_hide = set(sheet.data_c(c) for c in sheet.get_selected_columns())
sheet.hide_columns(
columns_to_hide,
data_indexes=True,
)
NOTE: columns (int) uses data column indexes, not displayed indexes. In other words the indexes of the columns which represent the underlying data are shown.
Notes:
Will return if all columns are currently displayed (Sheet.all_columns).
Example:
converting displayed column indexes to data indexes using data_c(c)
columns = set(sheet.data_c(c) for c in sheet.get_selected_columns())
hiding columns
sheet.hide_columns(
columns,
data_indexes=True,
)
showing them again
sheet.show_columns(columns)
Displayed column index to data
Convert a displayed column index to a data index. If the internal all_columns_displayed attribute is True then it will simply return the provided argument.
displayed_column_to_data(c)
data_c(c)
Get currently displayed columns
@property
displayed_columns() -> list[int]
e.g. columns = sheet.displayed_columns
Hiding Rows
Note that once you have hidden rows you can use the function displayed_row_to_data(row) to retrieve a row data index from a displayed index.
Display only certain rows
rows (int, iterable, "all") are the rows to be displayed, omit the rows to be hidden.
Use argument True with all_rows_displayed to display all rows, use False to display only the rows you've set using the rows arg.
You can also use the keyword argument all_displayed instead of all_rows_displayed.
Examples:
An example of row filtering using this function can be found here.
More examples below:
display all rows
self.sheet.display_rows("all")
display specific rows only
NOTE: rows (int) by default uses displayed row indexes, not data indexes. In other words the indexes of the rows displayed on the screen are the ones that are hidden, this is useful when used in conjunction with get_selected_rows().
data_indexes when False it makes the rows parameter indexes represent displayed rows and not the underlying Sheet data rows. When True the indexes represent data indexes.
Example:
rows_to_hide = set(sheet.data_r(r) for r in sheet.get_selected_rows())
sheet.hide_rows(
rows_to_hide,
data_indexes=True,
)
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}")
if name == "main":
set_dpi_awareness()
root = tk.Tk()
app = TableApp(root)
root.mainloop()
To implement checkboxes for boolean values (Yes/No) in your tksheet, follow these steps. Below are the code snippets you need to add or modify in your existing TableApp class. These changes will format specific columns to display checkboxes and allow users to toggle their state by clicking on them.
1. Define a Custom to_str_function for Checkboxes
Add the following method inside your TableApp class. This function will convert boolean values to checkbox symbols.
def bool_to_checkbox(self, val, **kwargs):
"""Convert boolean to checkbox symbols."""
return '☑' if val else '☐'
2. Apply the Checkbox Formatter to Specific Columns
In your load_selected_table method, after initializing the Sheet, apply the bool_formatter to the desired columns. Replace "C" with the column identifier(s) you want to format as checkboxes.
# Apply checkbox formatter to boolean columns
self.sheet.format(
"C", # Replace with your boolean column name or index
formatter_options=tksheet.bool_formatter(
to_str_function=self.bool_to_checkbox,
truthy={"yes", "Yes", "TRUE", "True", "true", "1", "☑"},
falsy={"no", "No", "FALSE", "False", "false", "0", "☐"},
),
)
If you have multiple boolean columns, you can apply the formatter to each column like this:
boolean_columns = ["C", "E"] # Replace with your boolean column names or indexes
for col in boolean_columns:
self.sheet.format(
col,
formatter_options=tksheet.bool_formatter(
to_str_function=self.bool_to_checkbox,
truthy={"yes", "Yes", "TRUE", "True", "true", "1", "☑"},
falsy={"no", "No", "FALSE", "False", "false", "0", "☐"},
),
)
3. Bind Click Events to Toggle Checkbox State
Still within the load_selected_table method, add an extra binding to handle single-click events, enabling users to toggle the checkbox state.
# Add checkbox toggle on single click
self.sheet.extra_bindings([
("single_click", self.toggle_checkbox)
])
4. Implement the Toggle Functionality
Add the following methods to your TableApp class. These methods will handle the toggling of boolean values when a checkbox is clicked.
def toggle_checkbox(self, event):
"""Toggle the boolean value of a checkbox cell."""
row = event[1]
column = event[2]
if self.is_bool_column(column):
current_value = self.current_sheet.get_cell_data(row, column)
new_value = not current_value
self.current_sheet.set_cell_data(row, column, new_value)
self.current_sheet.redraw()
self.on_cell_edit()
def is_bool_column(self, column):
"""Check if the specified column is a boolean column."""
bool_columns = ["C", "E"] # Replace with your boolean column names or indexes
headers = self.headers.get(self.current_table_name, [])
if isinstance(column, str):
return column in bool_columns
elif isinstance(column, int):
return headers[column] in bool_columns
return False
Explanation of the Methods:
toggle_checkbox: This method is triggered on a single click. It checks if the clicked cell is in a boolean column. If it is, it toggles the value (True to False or vice versa), updates the cell data, redraws the sheet to reflect the change, and calls on_cell_edit to handle any further processing.
is_bool_column: This method determines whether a given column is designated for boolean values. Update the bool_columns list with the appropriate column identifiers (either column names like "C", "E" or their respective indexes).
5. Ensure Column Identifiers Match Your Headers
Make sure that the identifiers used in the bool_columns list within the is_bool_column method match the actual columns you intend to format as boolean. You can use either column letters ("C") or zero-based column indexes (2 for the third column).
For example, if you're using column indexes:
def is_bool_column(self, column):
"""Check if the specified column index is a boolean column."""
bool_columns = [2, 4] # Replace with your boolean column indexes (0-based)
return column in bool_columns
6. Final Integration Example
Here's how the modified load_selected_table method might look with the above changes integrated:
def load_selected_table(self, table_name: str):
"""Display selected table."""
if self.current_sheet:
self.current_sheet.pack_forget()
self.current_sheet.destroy()
self.current_sheet = None
if self.selected_table_label:
try:
self.selected_table_label.config(bg=self.colors["button"])
except tk.TclError:
self.selected_table_label = None
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
)
# Apply checkbox formatter to boolean columns
boolean_columns = ["C"] # Replace with your boolean column names or indexes
for col in boolean_columns:
sheet.format(
col,
formatter_options=tksheet.bool_formatter(
to_str_function=self.bool_to_checkbox,
truthy={"yes", "Yes", "TRUE", "True", "true", "1", "☑"},
falsy={"no", "No", "FALSE", "False", "false", "0", "☐"},
),
)
# Add checkbox toggle on single click
sheet.extra_bindings([
("single_click", self.toggle_checkbox)
])
# Continue with existing sheet setup
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)
])
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
7. Final Touches
Ensure that the bool_to_checkbox, toggle_checkbox, and is_bool_column methods are correctly indented and placed within the TableApp class. Also, update the boolean_columns list to reflect the actual columns in your sheet that should display checkboxes.
With these changes, your tksheet will display checkboxes for specified boolean columns, allowing users to toggle Yes/No states with a single click.