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: Add the following text in the left upper corner of the header: Data > Table name (Name of the Table currently selected). Use a font size of 10 and use the following color for "Data >" color: #999999 for the rest use the default font. Remember to centralize all colors and fonts in def config_fonts(self): and def config_colors(self):. Python 3.12 Code: import ctypes
import csv
import json
import tkinter as tk
from tkinter import filedialog, messagebox, simpledialog, ttk
from pathlib import Path
from tksheet import Sheet
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:
"""Table Editor with sidebar and table management."""
def setup_ui(self):
"""Set up the user interface."""
self.create_sidebar()
self.create_main_frame()
self.create_header_frame()
self.create_table_frame()
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=[("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):
"""Add a new table."""
default_data = [["" for _ in range(5)] for _ in range(10)]
self.tables_data[table_name] = {"headers": self.headers.get(table_name, [""] * 5), "data": data or default_data}
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 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()
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.tables_data[table_name] = {"headers": headers, "data": table_data}
self.headers[table_name] = headers
self.create_table_label(table_name)
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.button_color)
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.default_font, header_font=self.default_font, auto_resize_columns=True)
sheet.set_options(table_fg=self.text_color, header_fg=self.text_color)
sheet.enable_bindings()
sheet.extra_bindings([("end_edit_cell", self.on_cell_edit)])
sheet.pack(expand=True, fill='both')
self.current_sheet = sheet
self.current_table_name = table_name
label = self.table_labels.get(table_name)
if label:
self.selected_table_label = label
try:
self.selected_table_label.config(bg=self.button_color_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.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:
self.tables_data[self.current_table_name]["data"] = self.current_sheet.get_sheet_data()
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):
"""Apply filter to table data."""
if not self.current_table_name or not self.current_sheet:
return
term = self.filter_entry.get().lower()
original_data = self.tables_data[self.current_table_name]["data"]
if term:
filtered_data = [row for row in original_data if any(term in str(cell).lower() for cell in row)]
else:
filtered_data = original_data
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
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}")
self.save_data()
def begin_rename(self, table_name: str):
"""Start renaming a table."""
if table_name not in self.table_labels:
messagebox.showerror("Error", f"Table '{table_name}' not found.")
return
label = self.table_labels[table_name]
self.cancel_rename()
self.rename_entry = tk.Entry(self.table_labels_frame, bg=label.cget("bg"), fg=self.text_color, relief='flat')
self.rename_entry.insert(0, table_name)
self.rename_entry.place(x=label.winfo_x(), y=label.winfo_y(), width=label.winfo_width(), height=label.winfo_height())
self.rename_entry.focus()
self.rename_entry.select_range(0, tk.END)
self.rename_entry.bind('', lambda event: self.end_rename(table_name))
self.rename_entry.bind('', lambda event: self.cancel_rename())
def end_rename(self, old_name: str):
"""Finalize table renaming."""
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_data 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:
self.update_table_name(old_name, new_name)
self.load_selected_table(new_name)
self.cancel_rename()
if name == "main":
set_dpi_awareness()
root = tk.Tk()
app = TableApp(root)
root.mainloop()
To achieve the functionality you requested, we'll need to update the config_fonts and config_colors methods to centralize the font sizes and colors, then modify the create_header_frame method to add the new label in the upper left corner.
Here's how you can implement these changes:
Update config_fonts to include the new font settings:
These changes will add the required label to the header. You may need to update the label's text dynamically whenever a new table is selected by setting self.current_table_name. Make sure to update self.data_label text accordingly.
It seems the issue arises because the default_font attribute was removed or renamed when updating the config_fonts method. It should create the individual font settings but also a font attribute for general use.
Here's a revised implementation of the config_fonts method to correctly set the self.default_font:
def config_fonts(self):
"""Configure app fonts."""
font_name, font_size, font_style = "Literata", 12, "normal"
self.default_font = (font_name, font_size, font_style)
self.data_label_font = (font_name, 10) # Use the font name and custom size for labels
self.root.option_add("*Font", f"{font_name} {font_size}")
Next, update where self.default_font is used to include the new font mapping, particularly focusing on places like the creation of widgets such as sheets or labels:
Adjust load_selected_table to use the new font attributes:
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 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.default_font,
header_font=self.default_font,
auto_resize_columns=True
)
sheet.set_options(table_fg=self.text_color, header_fg=self.text_color)
sheet.enable_bindings()
sheet.extra_bindings([("end_edit_cell", self.on_cell_edit)])
sheet.pack(expand=True, fill='both')
self.current_sheet = sheet
self.current_table_name = table_name
if label := self.table_labels.get(table_name):
self.selected_table_label = label
self.selected_table_label.config(bg=self.button_color_selected)
else:
self.selected_table_label = None
messagebox.showerror("Error", f"Label for '{table_name}' not found.")
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
By setting up self.default_font and self.data_label_font properly, you ensure that all related UI elements in your application are configured to use them correctly, solving the missing attribute error.