if name == "main":
app = SortableSheetApp()
app.mainloop()
To enable automatic reloading of column headers whenever a new column is created in your TkSheet, you need to refresh the headers of your comboboxes linked to column selections. This involves updating the values of the comboboxes whenever the headers change. Below, I'll show you how to extend your SortableSheetApp class to handle this use case.
Let's start by defining a method to update the combobox values whenever the headers change:
python
import tkinter as tk
from tkinter import ttk
from tksheet import Sheet
def custom_sort_design(master, style: ttk.Style, headers=None, sort_orders=None, colors=None):
"""Creates a custom sort frame with comboboxes for columns and sort order, includes secondary sort."""
sort_frame = ttk.Frame(master, style="Custom.TFrame")
# Configure styles
style.configure("Custom.TFrame", background=colors["background"], relief="flat", borderwidth=0)
style.configure("TCombobox", relief="flat", borderwidth=0, background=colors["background"], fieldbackground=colors["background"])
style.map("TCombobox", fieldbackground=[('readonly', colors["background"])], background=[('readonly', colors["background"])])
style.configure("Line.TFrame", background=colors["filter_line"])
# Create widgets for primary sort
primary_column_combobox = ttk.Combobox(sort_frame, values=headers, width=10, font=('Arial', 10), state="readonly")
primary_order_combobox = ttk.Combobox(sort_frame, values=sort_orders, width=10, font=('Arial', 10), state="readonly")
# Create widgets for secondary sort
secondary_column_combobox = ttk.Combobox(sort_frame, values=headers, width=10, font=('Arial', 10), state="readonly")
secondary_order_combobox = ttk.Combobox(sort_frame, values=sort_orders, width=10, font=('Arial', 10), state="readonly")
# Layout widgets
primary_column_combobox.grid(row=0, column=0, padx=5, pady=2, sticky='ew')
primary_order_combobox.grid(row=0, column=1, padx=5, pady=2, sticky='ew')
secondary_column_combobox.grid(row=1, column=0, padx=5, pady=2, sticky='ew')
secondary_order_combobox.grid(row=1, column=1, padx=5, pady=2, sticky='ew')
# Prevent text selection in comboboxes
for combobox in (primary_column_combobox, primary_order_combobox, secondary_column_combobox, secondary_order_combobox):
combobox.bind("<FocusIn>", lambda event: event.widget.selection_clear())
# Configure column weights
sort_frame.columnconfigure((0, 1), weight=1)
return (
sort_frame,
primary_column_combobox,
primary_order_combobox,
secondary_column_combobox,
secondary_order_combobox
)
class SortableSheetApp(tk.Tk):
"""Tkinter application with a sortable sheet."""
def __init__(self):
"""Initialize the sortable sheet application."""
super().__init__()
self.title("Sortable TkSheet Example")
self.data = [
["Apple", 10, 2.5],
["Banana", 5, 1.0],
["Apple", 15, 3.0],
["Orange", 8, 2.0],
["Banana", 12, 2.8],
["Apple", 20, 4.0],
["Orange", 10, 2.5],
]
self.headers = ["Fruit", "Quantity", "Price"]
self.sort_orders = ["Ascending", "Descending"]
# Define style
self.style = ttk.Style(self)
colors = {
"background": "#f0f0f0",
"filter_line": "#d9d9d9",
}
# Create custom sort frame
(
self.sort_frame,
self.primary_column_combobox,
self.primary_order_combobox,
self.secondary_column_combobox,
self.secondary_order_combobox
) = custom_sort_design(self, self.style, headers=self.headers, sort_orders=self.sort_orders, colors=colors)
self.sort_frame.pack(side="top", fill="x")
self.sheet = Sheet(self, data=self.data, headers=self.headers)
self.sheet.enable_bindings("all")
self.sheet.pack(expand=True, fill="both")
# Bind combobox changes to sorting
self.primary_column_combobox.bind("<<ComboboxSelected>>", lambda _: self.sort_data())
self.primary_order_combobox.bind("<<ComboboxSelected>>", lambda _: self.sort_data())
self.secondary_column_combobox.bind("<<ComboboxSelected>>", lambda _: self.sort_data())
self.secondary_order_combobox.bind("<<ComboboxSelected>>", lambda _: self.sort_data())
# Set default selections and sort initially
self.primary_column_combobox.set(self.headers[0])
self.primary_order_combobox.set(self.sort_orders[0])
self.secondary_column_combobox.set(self.headers[0])
self.secondary_order_combobox.set(self.sort_orders[0])
self.sort_data()
def sort_data(self):
"""Sort data based on the dropdown selections for primary and secondary sorts."""
primary_column = self.primary_column_combobox.get()
primary_ascending = self.primary_order_combobox.get() == "Ascending"
secondary_column = self.secondary_column_combobox.get()
secondary_ascending = self.secondary_order_combobox.get() == "Ascending"
primary_index = self.headers.index(primary_column)
secondary_index = self.headers.index(secondary_column)
# Sort the data
self.data.sort(
key=lambda row: (
self.get_sortable_value(row[primary_index]),
self.get_sortable_value(row[secondary_index])
),
reverse=not primary_ascending
)
self.sheet.set_sheet_data(self.data)
def get_sortable_value(self, value):
"""Convert value to a sortable format."""
return str(value) # Convert everything to a string for default sorting behavior
def update_headers(self, new_headers):
"""Update combobox headers after columns are added or changed."""
self.headers = new_headers
self.primary_column_combobox['values'] = self.headers
self.secondary_column_combobox['values'] = self.headers
# Reset combobox selections if current selection is not in the new headers
if self.primary_column_combobox.get() not in self.headers:
self.primary_column_combobox.set(self.headers[0])
if self.secondary_column_combobox.get() not in self.headers:
self.secondary_column_combobox.set(self.headers[0])
# Below is a simple demonstration of adding a new column and updating the headers
if __name__ == "__main__":
app = SortableSheetApp()
# Example of dynamically adding a new column
app.data = [row + [str(idx)] for idx, row in enumerate(app.data)]
app.headers.append("Index")
app.update_headers(app.headers)
app.mainloop()
Explanation:
update_headers Method: This method is designed to update the combobox's available headers whenever you modify column headers, ensuring the current selection remains valid.
Adding a New Column: You can simulate dynamically appending a column by editing the data and headers attributes. Consequently, call update_headers() to refresh the combobox values.
Resetting Combobox Selections: After modifying the available headers, it checks if the current selection is still valid. If not, it resets the selections.
This design assumes that the changes to headers happen during runtime, requiring that update_headers() is called with the new header list whenever columns change.