Certainly! To modify your TableApp so that the tksheet tables automatically adjust their column widths based on the window size, you can utilize the auto_resize_columns option provided by tksheet. This ensures that the columns expand or contract to fill the available space, making your application more responsive and user-friendly.
Below is the completely revised and corrected version of your program with detailed explanations of the changes made to achieve the desired functionality.
Revised TableApp Code
import tkinter as tk
from tkinter import simpledialog, messagebox, filedialog
from tksheet import Sheet
import json
import csv
from pathlib import Path
import ctypes
def set_dpi_awareness():
"""Enable DPI awareness for high DPI settings."""
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception as e:
print(f"Error setting DPI awareness: {e}")
class TableApp:
def __init__(self, root):
"""Initialize the Table Editor application."""
self.root = root
self.root.title("Table Editor with Sidebar")
self.root.geometry("1280x720")
# Font Configurations
font_name = "Literata"
font_size = 12
font_style = "normal"
self.default_font = (font_name, font_size, font_style)
self.root.option_add("*Font", f"{font_name} {font_size}")
# Color Configurations
self.TEXT_COLOR = '#333333'
self.BACKGROUND_COLOR = '#FFFFFF'
self.SIDEBAR_COLOR = '#F7F8FC'
self.BUTTON_COLOR = '#F7F8FC'
self.BUTTON_COLOR_SELECTED = '#EAEDEF'
# Initialize UI and Data
self.setup_ui()
self.initialize_data()
self.load_tables()
def setup_ui(self):
"""Set up the user interface components."""
self.create_sidebar()
self.create_main_frame()
self.create_header_frame()
self.create_table_frame()
def create_sidebar(self):
"""Create the sidebar and its components."""
# Sidebar Frame
self.sidebar = tk.Frame(self.root, width=200, bg=self.SIDEBAR_COLOR, bd=0, relief='flat')
self.sidebar.pack(expand=False, fill='y', side='left', anchor='nw')
# Separator Frame (fixed width to avoid taking up too much space)
self.separator = tk.Frame(self.root, width=2, bg=self.BACKGROUND_COLOR, bd=0, relief='flat')
self.separator.pack(expand=False, fill='y', side='left', anchor='nw')
# Sidebar Buttons
self.new_table_label = self.create_clickable_label(
self.sidebar, "Create New Table", self.create_new_table)
self.new_table_label.pack(padx=10, pady=10, fill='x')
self.import_table_label = self.create_clickable_label(
self.sidebar, "Import Table", self.import_file)
self.import_table_label.pack(padx=10, pady=10, fill='x')
# Frame to Hold Table Labels
self.table_labels_frame = tk.Frame(self.sidebar, bg=self.SIDEBAR_COLOR)
self.table_labels_frame.pack(expand=True, fill='both', padx=10, pady=10)
# Delete Table Option
self.delete_table_label = self.create_clickable_label(
self.sidebar, "Delete Selected Table", self.delete_table)
self.delete_table_label.pack(side='bottom', padx=10, pady=10, fill='x')
# Add Hover Effects
self.add_custom_hover(self.new_table_label)
self.add_custom_hover(self.import_table_label)
self.add_custom_hover(self.delete_table_label)
def create_main_frame(self):
"""Create the main frame of the application."""
self.main_frame = tk.Frame(self.root, bg=self.BACKGROUND_COLOR)
self.main_frame.pack(expand=True, fill='both', side='right')
def create_header_frame(self):
"""Create the header frame with filter and rename options."""
self.header_frame = tk.Frame(self.main_frame, height=50, bg=self.BACKGROUND_COLOR)
self.header_frame.pack(fill='x')
# Filter Label and Entry
self.filter_label = tk.Label(self.header_frame, text="Filter:", bg=self.BACKGROUND_COLOR, fg=self.TEXT_COLOR, anchor="w")
self.filter_label.pack(side='left', padx=5, pady=10)
self.filter_entry = tk.Entry(self.header_frame, fg=self.TEXT_COLOR)
self.filter_entry.pack(side='left', padx=5, pady=10)
self.filter_entry.bind("<KeyRelease>", lambda event: self.apply_filter())
# Rename Headers Button
self.rename_headers_label = self.create_clickable_label(
self.header_frame, "Rename Headers", self.rename_headers, allow_rename=False)
self.rename_headers_label.pack(side='left', padx=5, pady=10, fill='x')
def create_table_frame(self):
"""Create the frame to hold the table."""
self.table_frame = tk.Frame(self.main_frame, bg=self.BACKGROUND_COLOR)
self.table_frame.pack(expand=True, fill='both')
def initialize_data(self):
"""Initialize data structures and variables."""
self.save_file_dir = Path("tables")
self.tables = {}
self.table_labels = {}
self.original_data = {}
self.headers = {}
self.current_table_name = None
self.rename_entry = None
self.selected_table_label = None
self.save_file_dir.mkdir(exist_ok=True)
def create_clickable_label(self, parent, text, command, allow_rename=True):
"""Create a clickable Label widget."""
label = tk.Label(
parent, text=text, bg=self.BUTTON_COLOR, fg=self.TEXT_COLOR,
borderwidth=0, relief='flat', cursor='hand2', anchor='w',
padx=10, pady=5
)
label.bind("<Button-1>", lambda e: command())
if allow_rename:
label.bind("<Double-Button-1>", lambda e, name=text: self.begin_rename(name))
return label
def create_new_table(self):
"""Create a new table and add it to the available tables list."""
table_name = f"Table {len(self.tables) + 1}"
self.add_table(table_name)
self.load_selected_table(table_name)
def import_file(self):
"""Import a CSV or JSON file to create a new table."""
file_path = filedialog.askopenfilename(
title="Open File",
filetypes=[("CSV files", ".csv"), ("JSON files", ".json")]
)
if not file_path:
return
try:
if file_path.endswith('.csv'):
with open(file_path, newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
data = list(reader)
headers, table_data = data[0], data[1:]
elif file_path.endswith('.json'):
with open(file_path, 'r', encoding='utf-8') as jsonfile:
data = json.load(jsonfile)
headers, table_data = data[0], data[1:]
else:
messagebox.showerror("Unsupported File", "The selected file format is not supported.")
return
except Exception as e:
messagebox.showerror("Import Error", f"An error occurred while importing the file:\n{e}")
return
table_name = Path(file_path).stem
self.add_table(table_name, table_data, headers=headers)
self.load_selected_table(table_name)
def add_table(self, table_name, data=None, headers=None):
"""Add a table to the UI and internal storage."""
default_headers = headers if headers else [f"Column {i+1}" for i in range(5)]
default_data = data if data else [["" for _ in range(len(default_headers))] for _ in range(10)]
# Initialize tksheet Sheet
sheet = Sheet(
self.table_frame,
data=default_data,
headers=default_headers,
show_table=True,
show_headers=True,
height=300, # Adjust as needed
width=400, # Initial width; will auto-resize
auto_resize_columns=True, # Enable auto-resizing of columns
font=self.default_font,
header_font=self.default_font,
row_height=20,
header_height=25,
column_width=100, # Default column width; will be overridden by auto_resize
)
# Configure Sheet Options
sheet.set_options(
table_fg=self.TEXT_COLOR,
header_fg=self.TEXT_COLOR,
entry_fg=self.TEXT_COLOR,
entry_bg=self.BACKGROUND_COLOR,
entry_selected_bg='#CCE4FF',
header_bg='#D3D3D3',
header_selected_bg='#A9A9A9',
# Ensure that auto_resize_columns is enabled
auto_resize_columns=True,
)
sheet.enable_bindings((
"single_select",
"column_select",
"row_select",
"column_width_resize",
"double_click_column_resize",
"arrowkeys",
"right_click_popup_menu",
"rc_select",
"drag_select",
"column_drag_and_drop",
"row_drag_and_drop",
"cut",
"copy",
"paste",
"delete",
"undo",
"edit_cell"))
# Extra Bindings to Save Data on Edit
sheet.extra_bindings([
("end_edit_cell", lambda event, tn=table_name: self.save_data(tn)),
])
# Pack the sheet but keep it hidden initially
sheet.pack(expand=True, fill='both')
sheet.pack_forget()
# Store Data
self.tables[table_name] = sheet
self.original_data[table_name] = sheet.get_sheet_data()
self.headers[table_name] = sheet.headers()
# Create Sidebar Label for the Table
table_label = self.create_clickable_label(
self.table_labels_frame, table_name,
lambda name=table_name: self.load_selected_table(name)
)
table_label.pack(fill='x', pady=2)
self.table_labels[table_name] = table_label
# Add Hover Effect
self.add_custom_hover(table_label)
def delete_table(self):
"""Delete the currently selected table."""
if not self.current_table_name:
messagebox.showwarning("No Table Selected", "Please select a table to delete.")
return
response = messagebox.askyesno(
"Delete Table",
f"Are you sure you want to delete the table '{self.current_table_name}'?"
)
if response:
# Remove from the UI
self.tables[self.current_table_name].destroy()
self.table_labels[self.current_table_name].destroy()
# Remove from internal storage
del self.tables[self.current_table_name]
del self.original_data[self.current_table_name]
del self.headers[self.current_table_name]
del self.table_labels[self.current_table_name]
# Remove from disk
file_path = self.save_file_dir / f"{self.current_table_name}.json"
if file_path.exists():
file_path.unlink()
# Reset current table selection
self.current_table_name = None
self.selected_table_label = None
def load_tables(self):
"""Load existing tables from the directory."""
for file_path in self.save_file_dir.glob("*.json"):
table_name = file_path.stem
with file_path.open('r') as file:
data = json.load(file)
headers, table_data = data[0], data[1:]
self.add_table(table_name, table_data, headers=headers)
def load_selected_table(self, table_name):
"""Display the selected table and hide others."""
for name, sheet in self.tables.items():
if name == table_name:
sheet.headers(self.headers[name])
sheet.set_sheet_data(self.original_data[name])
sheet.pack(expand=True, fill='both')
self.current_table_name = table_name
# Highlight the selected table label
if self.selected_table_label:
self.selected_table_label.config(bg=self.BUTTON_COLOR)
selected_label = self.table_labels[name]
selected_label.config(bg=self.BUTTON_COLOR_SELECTED)
self.selected_table_label = selected_label
else:
sheet.pack_forget()
self.table_labels[name].config(bg=self.BUTTON_COLOR)
def save_data(self, table_name):
"""Save current data of a table to a file."""
data = [self.headers[table_name]] + self.tables[table_name].get_sheet_data()
file_path = self.save_file_dir / f"{table_name}.json"
try:
with file_path.open('w') as file:
json.dump(data, file, indent=4)
print(f"Data for '{table_name}' saved successfully.")
# Update original data
self.original_data[table_name] = self.tables[table_name].get_sheet_data()
except Exception as e:
messagebox.showerror("Save Error", f"An error occurred while saving the data:\n{e}")
def apply_filter(self):
"""Apply filtering based on the entered term."""
if not self.current_table_name:
return
term = self.filter_entry.get().lower()
original_data = self.original_data[self.current_table_name]
if term == "":
# If filter is empty, show original data
filtered_data = original_data
else:
filtered_data = [
row for row in original_data
if any(term in str(cell).lower() for cell in row)
]
self.tables[self.current_table_name].set_sheet_data(filtered_data)
def rename_headers(self):
"""Prompt user to rename headers of the currently selected table."""
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 len(header_list) != len(current_headers):
messagebox.showerror("Invalid Headers", "The number of headers must match the existing number.")
return
self.headers[self.current_table_name] = header_list
self.tables[self.current_table_name].headers(header_list)
self.save_data(self.current_table_name)
def begin_rename(self, table_name):
"""Begin renaming of the table with a double click."""
label = self.table_labels[table_name]
if self.rename_entry:
self.rename_entry.destroy()
label.update_idletasks()
label_x, label_y = label.winfo_x(), label.winfo_y()
label_width, label_height = label.winfo_width(), label.winfo_height()
self.rename_entry = tk.Entry(
self.table_labels_frame,
bg=label.cget("bg"),
fg=self.TEXT_COLOR,
relief='flat',
borderwidth=0,
highlightthickness=0,
justify='left'
)
self.rename_entry.insert(0, table_name)
self.rename_entry.place(x=label_x, y=label_y, width=label_width, height=label_height)
self.rename_entry.focus()
self.rename_entry.select_range(0, tk.END)
self.rename_entry.bind('<Return>', lambda event: self.end_rename(table_name))
self.rename_entry.bind('<FocusOut>', lambda event: self.cancel_rename())
def end_rename(self, old_name):
"""Finish the renaming process for the specified table."""
new_name = self.rename_entry.get().strip()
if not new_name:
messagebox.showerror("Invalid Name", "Table name cannot be empty.")
self.rename_entry.focus_set()
return
if new_name in self.tables and new_name != old_name:
messagebox.showerror("Duplicate Name", f"A table named '{new_name}' already exists.")
self.rename_entry.focus_set()
return
if new_name != old_name:
# Rename internal storage
self.tables[new_name] = self.tables.pop(old_name)
self.original_data[new_name] = self.original_data.pop(old_name)
self.headers[new_name] = self.headers.pop(old_name)
# Rename label
self.table_labels[new_name] = self.table_labels.pop(old_name)
self.table_labels[new_name].config(text=new_name)
# Update selected label if necessary
if self.selected_table_label and self.selected_table_label == self.table_labels[new_name]:
self.selected_table_label = self.table_labels[new_name]
self.table_labels[new_name].config(bg=self.BUTTON_COLOR_SELECTED)
else:
self.table_labels[new_name].config(bg=self.BUTTON_COLOR)
# Rename file on disk
current_file = self.save_file_dir / f"{old_name}.json"
new_file = self.save_file_dir / f"{new_name}.json"
if current_file.exists():
current_file.rename(new_file)
# Update current table name if it was the renamed table
if self.current_table_name == old_name:
self.current_table_name = new_name
self.cancel_rename()
def cancel_rename(self):
"""Cancel the renaming entry."""
if self.rename_entry:
self.rename_entry.destroy()
self.rename_entry = None
def add_custom_hover(self, label):
"""Add custom hover effects to a label."""
def on_enter(e):
if label != self.selected_table_label:
label.config(bg=self.BUTTON_COLOR_SELECTED)
def on_leave(e):
if label != self.selected_table_label:
label.config(bg=self.BUTTON_COLOR)
label.bind("<Enter>", on_enter)
label.bind("<Leave>", on_leave)
if __name__ == "__main__":
set_dpi_awareness()
root = tk.Tk()
app = TableApp(root)
root.mainloop()
Key Changes and Explanations
-
Indentation and Structure Fixes:
- Issue: The original code had inconsistent indentation, making it syntactically incorrect.
- Fix: Proper indentation has been applied to ensure that all methods are correctly nested within the
TableApp class.
-
Enable auto_resize_columns:
- Implementation: In the
add_table method, the Sheet widget is initialized with auto_resize_columns=True. Additionally, it's reinforced in the set_options method to ensure that column auto-resizing is active.
- Purpose: This ensures that columns automatically adjust their widths based on the available space whenever the window is resized.
-
Separator Frame Adjustment:
- Change: Reduced the separator width from
100 to 2 pixels.
- Reason: A very wide separator can consume unnecessary space, making the table area too narrow. A thinner separator maintains the visual distinction without taking up much space.
-
Clickable Labels Enhanced:
- Modification: Changed the cursor for clickable labels to
hand2 to indicate interactivity.
- Benefit: Improves user experience by providing visual feedback that the labels are interactive.
-
Error Handling in import_file and save_data:
- Addition: Wrapped file operations in
try-except blocks.
- Advantage: Prevents the application from crashing due to unforeseen errors during file import or save operations and provides user-friendly error messages.
-
Responsive UI Enhancements:
- Adjustment: Set
expand=True and fill='both' for the Sheet widget's packing.
- Outcome: Ensures that the table expands to fill the available space within the main frame, making the UI more flexible and responsive to window resizing.
-
Header Renaming Constraints:
How the auto_resize_columns Works
The auto_resize_columns=True option in the tksheet widget automatically adjusts the widths of the columns to fit the available space. Here's how it integrates into the application:
-
Initialization:
sheet = Sheet(
self.table_frame,
data=default_data,
headers=default_headers,
show_table=True,
show_headers=True,
height=300,
width=400,
auto_resize_columns=True, # Enables auto-resizing
font=self.default_font,
header_font=self.default_font,
row_height=20,
header_height=25,
column_width=100,
)
-
Options Configuration:
sheet.set_options(
table_fg=self.TEXT_COLOR,
header_fg=self.TEXT_COLOR,
entry_fg=self.TEXT_COLOR,
entry_bg=self.BACKGROUND_COLOR,
entry_selected_bg='#CCE4FF',
header_bg='#D3D3D3',
header_selected_bg='#A9A9A9',
auto_resize_columns=True, # Reinforces auto-resizing
)
With these settings, whenever the main window is resized, the tksheet table automatically recalculates and adjusts the column widths to optimally use the available space. This creates a fluid and adaptable user interface where the table remains proportionate to the window size.
Additional Recommendations
-
Minimum Column Widths:
- Suggestion: To prevent columns from becoming too narrow, consider setting a minimum column width.
- Implementation: While
tksheet doesn't provide a direct min_column_width option, you can handle it by adjusting the auto_resize behavior or implementing custom logic in the resize bindings.
-
Scrollbar Integration:
- Enhancement: If you anticipate tables with many columns, integrating horizontal scrollbars can improve usability.
- Implementation:
tksheet supports horizontal scrolling out of the box when columns exceed the visible area.
-
Persisting Window Size:
- Feature: Save and restore the window size between sessions to enhance user experience.
- Method: Store the window dimensions in a configuration file and apply them on startup.
-
Advanced Filtering:
- Upgrade: Implement more sophisticated filtering options, such as column-specific filters or regex-based searches.
- Benefit: Provides users with more control over how they view and analyze data.
-
Export Functionality:
- Addition: Add options to export tables back to CSV or JSON formats.
- Advantage: Enhances the app's utility by allowing data to be easily shared or used in other applications.
By implementing these changes and recommendations, your TableApp will offer a more robust, user-friendly, and responsive experience. The automatic resizing of columns ensures that your tables remain readable and well-formatted across different window sizes and resolutions.
If you encounter any further issues or need additional features, feel free to ask!