modify the programm so that the tksheet tables columkn widths automaticly adjust to the width and fill the rest of the window that are not filled by the sidebar and the seperator between the sidebar and the tksheet table. Use this infomration: To adjust the column size in tksheet according to the window size, you can use the auto_resize_columns option. This option allows columns to automatically resize to fit the width of the window
. Here's an example:
python
import tksheet
import tkinter as tk
Create the main window
root = tk.Tk()
Create a tksheet widget
sheet = tksheet.Sheet(root)
sheet.pack(expand=True, fill='both')
Sample data with headers
data = [
['Header 1', 'Header 2', 'Header 3'],
[1, 2, 3],
[4, 5, 6]
]
Insert data into the sheet
sheet.set_sheet_data(data)
Set auto resize columns option
sheet.set_options(auto_resize_columns=True)
Start the main loop
root.mainloop()
In this example, the auto_resize_columns option is set to True, which makes the columns automatically resize to fit the width of the window
.
Does this help with what you were trying to achieve?
Python 3.12: 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
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."""
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')
optimize so that the columns adjust to their largest field and then afterwards all adjust to the window size if they do not fit in the window than it goes above the window (scrollbar to the side)
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
def create_main_frame(self):
"""Create the main frame of the application."""
self.main_frame = tk.Frame(self.root)
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')
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 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
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
def add_table(self, table_name, data=None):
"""Add a table to the UI and internal storage."""
default_data = [["" for _ in range(5)] for _ in range(10)]
self.tables[table_name] = Sheet(
self.table_frame,
data=data or default_data,
show_table=True,
headers=None,
font=self.default_font, # Use default font
header_font=self.default_font, # Set the header font
)
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:
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()
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 = data.pop(0)
self.add_table(table_name, data)
self.headers[table_name] = 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.pack(expand=True, fill='both')
self.current_table_name = table_name
sheet.headers(self.headers[name])
self.apply_filter()
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"
with file_path.open('w') as file:
json.dump(data, file)
print(f"Data for {table_name} saved successfully.")
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]
filtered_data = [
row for row in original_data
if any(term in str(cell).lower() for cell in row)
]
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
if new_headers:
header_list = [header.strip() for header in new_headers.split(',')]
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]
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 current_file.exists():
current_file.rename(new_file)
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("", on_enter)
label.bind("", on_leave)
if name == "main":
set_dpi_awareness()
root = tk.Tk()
app = TableApp(root)
root.mainloop()
To modify your program so that the tksheet tables' column widths automatically adjust to fit the width of the window (excluding the sidebar and the separator), you can incorporate the auto_resize_columns option provided by tksheet.
Here's how you can modify your add_table method to achieve this:
Update the creation of the Sheet instance to include the auto_resize_columns option set to True.
Ensure that the Sheet widget is packed to expand and fill the available space within its parent frame (self.table_frame).
Below is the updated add_table method with these modifications:
def add_table(self, table_name, data=None):
"""Add a table to the UI and internal storage."""
default_data = [["" for _ in range(5)] for _ in range(10)]
self.tables[table_name] = Sheet(
self.table_frame,
data=data or default_data,
show_table=True,
headers=None,
font=self.default_font, # Use default font
header_font=self.default_font, # Set the header font
auto_resize_columns=True # Enable automatic column resizing
)
# Set table and header foreground colors
self.tables[table_name].set_options(
table_fg=self.TEXT_COLOR, header_fg=self.TEXT_COLOR
)
# Enable necessary bindings
self.tables[table_name].enable_bindings()
# Bind end of cell edit to save data
self.tables[table_name].extra_bindings([
("end_edit_cell", lambda event, tn=table_name: self.save_data(tn)),
])
# Initially hide the sheet
self.tables[table_name].pack_forget()
self.original_data[table_name] = self.tables[table_name].get_sheet_data()
if table_name not in self.headers:
self.headers[table_name] = self.tables[table_name].headers()
# Create a clickable label for the table in the sidebar
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 to the table label
self.add_custom_hover(table_label)
With this change, your tksheet widgets should now automatically adjust their column widths according to the available window size, effectively filling the space not occupied by the sidebar and separator.
Ensure your table frame (self.table_frame) is set to expand and fill both directions, which allows the Sheet to take up the available space:
self.table_frame.pack(expand=True, fill='both')
These changes should address the requirement of having the columns resize dynamically with the window size changes.
To achieve the desired behavior where columns initially adjust to fit their largest field and then expand or contract to fit the window (with scrollbars appearing if necessary), you'll need a combination of strategies:
Calculate the Widths: Initially calculate the width of each column based on its largest entry.
Fit to Window: Adjust these initial widths, so they either fit the window perfectly or add a scrollbar when exceeding the window width.
Use Scrollbars: Enable scrollbars for horizontal navigation when needed.
Here's how you can implement this logic in your add_table method:
def add_table(self, table_name, data=None):
"""Add a table to the UI and internal storage."""
# Sample default data
default_data = [["" for _ in range(5)] for _ in range(10)]
data = data or default_data
# Create the sheet
sheet = Sheet(
self.table_frame,
data=data,
show_table=True,
headers=None,
font=self.default_font,
header_font=self.default_font,
)
# Set table and header foreground colors
sheet.set_options(
table_fg=self.TEXT_COLOR, header_fg=self.TEXT_COLOR
)
# Calculate the maximum width needed for each column
column_widths = []
for col_idx in range(len(data[0])):
max_width = max(sheet.measure(cell, sheet.get_fonts()[0]) for cell in [row[col_idx] for row in data])
column_widths.append(max_width)
# Apply the calculated widths
for col_idx, max_width in enumerate(column_widths):
sheet.column_width(col_idx, width=max_width)
# Enable scrollbars
sheet.enable_bindings(
("single_select",
"row_select",
"column_select",
"drag_select",
"select_all",
"type_select",
"toggle_select",
"toggle_select_hold",
),
)
sheet.grid(row=0, column=0, sticky='nswe')
xscroll = tk.Scrollbar(self.main_frame, orient='horizontal', command=sheet.set_xviews)
sheet.configure(xscrollcommand=xscroll.set)
xscroll.grid(row=1, column=0, sticky='ew')
yscroll = tk.Scrollbar(self.main_frame, orient='vertical', command=sheet.set_yviews)
sheet.configure(yscrollcommand=yscroll.set)
yscroll.grid(row=0, column=1, sticky='ns')
self.tables[table_name] = sheet
self.original_data[table_name] = sheet.get_sheet_data()
if table_name not in self.headers:
self.headers[table_name] = sheet.headers()
# Create a clickable label for the table in the sidebar
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 to the table label
self.add_custom_hover(table_label)
Key Points:
Column Width Calculation: The code measures the string width using sheet.measure(), setting the column widths based on the widest content.
Scrollbar Integration: Both horizontal (xscroll) and vertical (yscroll) scrollbars are added and linked with the Sheet widget.
Dynamic Resizing: After initial measurement and setup, the tksheet adjusts to its largest elements and then deals with overflow using scrollbars.
Additional Considerations:
Ensure you have the layout configured in such a way that the self.main_frame widget (where your sheet is presumably added) accepts the grid configuration to manage the positioning of the scrollbars properly.