Build a GUI program based on tksheet that allows the creation of tables and editing of tables to save large amount of data. The data should be saved automatically. Use python 3.12 and modern features where useful.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To create a GUI program using Python 3.12 with the tksheet module for table creation and editing, we will also use tkinter for the graphical interface. The program will include features to automatically save data periodically. Below is a simple example to help you get started:
Prerequisites
First, make sure you have installed the tksheet library. If not, you can install it using pip:
bash
pip install tksheet
GUI Program with Auto-Save Functionality
Here is a basic implementation of a GUI using tksheet and tkinter that supports editing tables and automatically saves the data to a file every minute.
python
import tkinter as tk
from tksheet import Sheet
import threading
import json
import os
class TableApp:
def __init__(self, root):
self.root = root
self.root.title("Table Editor with Auto-Save")
# Initialize sheet
self.sheet = Sheet(root, data=[["" for _ in range(5)] for _ in range(10)])
self.sheet.enable_bindings()
self.sheet.pack(expand=True, fill='both')
self.auto_save_interval = 60 # seconds
self.save_file_path = "table_data.json"
# Load existing data if available
self.load_data()
# Start auto-save thread
self.auto_save_thread = threading.Thread(target=self.auto_save, daemon=True)
self.auto_save_thread.start()
def load_data(self):
"""Load data from the file if it exists."""
if os.path.exists(self.save_file_path):
with open(self.save_file_path, 'r') as file:
data = json.load(file)
self.sheet.set_sheet_data(data)
print("Data loaded successfully.")
def save_data(self):
"""Save current data to a file."""
data = self.sheet.get_sheet_data()
with open(self.save_file_path, 'w') as file:
json.dump(data, file)
print("Data saved successfully.")
def auto_save(self):
"""Automatically save data at regular intervals."""
while True:
self.save_data()
threading.Event().wait(self.auto_save_interval)
if __name__ == "__main__":
root = tk.Tk()
app = TableApp(root)
root.mainloop()
Explanation
tksheet: This module provides a widget similar to Excel or Google Sheets, which allows tabular data representation in a tkinter application.
Data Handling: The data is initialized in the sheet with 10 rows and 5 columns. You can change these dimensions based on your requirements.
Auto-Save Feature: The program automatically saves the table's data to a JSON file every minute using a separate thread, ensuring the UI remains responsive.
Load Data: On startup, the program attempts to load existing data from a file to preserve previous session work.
Threading for Auto-Save: A separate thread is used for auto-saving to avoid blocking the main UI thread.
This implementation provides a basic structure that you can expand upon with additional features like manual save buttons, exploring more sophisticated file formats, and adding more complex interaction features with tksheet.
User
Save the data automaticly after every change.
Assistant
To implement automatic saving of data after each change in the tksheet, you can leverage the binding capabilities of tksheet. Specifically, you can bind to the event that signifies a change in the cell data. Here's how you can modify the existing program to achieve this behavior:
python
import tkinter as tk
from tksheet import Sheet
import json
import os
class TableApp:
def __init__(self, root):
self.root = root
self.root.title("Table Editor with Auto-Save on Change")
# Initialize sheet
self.sheet = Sheet(root, data=[["" for _ in range(5)] for _ in range(10)])
self.sheet.enable_bindings()
# Bind the sheet to save data on cell change
self.sheet.extra_bindings([
("end_edit_cell", self.on_cell_change),
])
self.sheet.pack(expand=True, fill='both')
self.save_file_path = "table_data.json"
# Load existing data if available
self.load_data()
def load_data(self):
"""Load data from the file if it exists."""
if os.path.exists(self.save_file_path):
with open(self.save_file_path, 'r') as file:
data = json.load(file)
self.sheet.set_sheet_data(data)
print("Data loaded successfully.")
def save_data(self):
"""Save current data to a file."""
data = self.sheet.get_sheet_data()
with open(self.save_file_path, 'w') as file:
json.dump(data, file)
print("Data saved successfully.")
def on_cell_change(self, event):
"""Callback function to save data whenever a cell value changes."""
self.save_data()
if __name__ == "__main__":
root = tk.Tk()
app = TableApp(root)
root.mainloop()
User
Add a sidebar to the GUI. In the sidebar add a button to create new tables and have a list with the available tables
Assistant
To add a sidebar to the GUI with a button to create new tables and a list of available tables, we'll enhance the current application structure. We will use a tkinter.Frame to represent the sidebar and add controls for interacting with multiple tables. Here's the updated code:
python
User
modify the sidebar to be flat) and have the following color throughout: #F7F8FC
Assistant
To modify the sidebar so that it has a flat appearance and a uniform color throughout, we can adjust the styling of the sidebar by changing the bg attribute and ensuring any widgets inside it blend seamlessly with the same background color. Here's how you can adjust the program to achieve this:
python
User
enable high dpi support an open the window at 600 x 600
Assistant
To support high DPI settings in Tkinter, you can enable DPI awareness, which ensures that your application scales correctly on high-resolution displays. We also need to set the initial window size to 600x600 pixels. Here's how you can update the application to include these features:
python
User
implement filters to filter rows based on terms
Assistant
To implement row filtering based on search terms in the tksheet table, we can add a text entry widget and a search button to the sidebar. When the user enters a term and hits the search button, the displayed rows in the current table are filtered according to the term. Here's how you can implement that:
python
User
Insert a header above the tables but it should not go above the sidebar. Move the fiter to the new header
Assistant
To create a header that includes filtering functionality and does not overlap with the sidebar, you need to restructure the layout a bit. We'll move the filter components from the sidebar to this new header.
Event Binding: The extra_bindings() method in tksheet allows us to specify custom bindings. We use the "end_edit_cell" event, which triggers every time a cell's editing is completed and the value changes.
Immediate Save: When a cell value changes, the on_cell_change method is called, which in turn calls save_data(). This saves the current state of the table to a JSON file immediately after a change.
Efficiency Consideration: While this approach saves data after every change, it also means that saving occurs frequently, potentially causing performance issues for very large datasets or if the saving process is not optimized. Consider optimizing the saving process or adjusting frequency if this becomes an issue.
This setup ensures that there is minimal data loss risk, as changes are saved in real-time as they occur, while keeping the interface responsive and user-friendly.
import tkinter as tk
from tksheet import Sheet
import json
import os
class TableApp:
def __init__(self, root):
self.root = root
self.root.title("Table Editor with Sidebar")
# Create main layout frames
self.sidebar = tk.Frame(root, width=200, bg='lightgray')
self.sidebar.pack(expand=False, fill='y', side='left', anchor='nw')
self.table_frame = tk.Frame(root)
self.table_frame.pack(expand=True, fill='both', side='right')
# Sidebar components
self.new_table_button = tk.Button(self.sidebar, text="New Table", command=self.create_new_table)
self.new_table_button.pack(padx=10, pady=10)
self.table_listbox = tk.Listbox(self.sidebar)
self.table_listbox.pack(expand=True, fill='both', padx=10, pady=10)
self.table_listbox.bind('<<ListboxSelect>>', self.load_selected_table)
self.save_file_dir = "tables"
self.tables = {} # Dictionary to hold table names and Sheet objects
if not os.path.exists(self.save_file_dir):
os.makedirs(self.save_file_dir)
self.load_tables()
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.tables[table_name] = Sheet(self.table_frame, data=[["" for _ in range(5)] for _ in range(10)])
self.tables[table_name].enable_bindings()
self.tables[table_name].extra_bindings([
("end_edit_cell", lambda event, table_name=table_name: self.save_data(table_name)),
])
self.tables[table_name].pack_forget() # Initially, hide the new table
self.table_listbox.insert('end', table_name)
self.table_listbox.select_set('end')
self.load_selected_table()
def load_tables(self):
"""Load existing tables from the directory."""
for filename in os.listdir(self.save_file_dir):
if filename.endswith(".json"):
table_name = filename[:-5] # Remove '.json' to get table name
self.table_listbox.insert('end', table_name)
self.tables[table_name] = Sheet(self.table_frame)
self.tables[table_name].enable_bindings()
self.tables[table_name].extra_bindings([
("end_edit_cell", lambda event, table_name=table_name: self.save_data(table_name)),
])
with open(os.path.join(self.save_file_dir, filename), 'r') as file:
data = json.load(file)
self.tables[table_name].set_sheet_data(data)
self.tables[table_name].pack_forget()
def load_selected_table(self, event=None):
"""Display the selected table and hide others."""
selection = self.table_listbox.curselection()
if selection:
for table_name, sheet in self.tables.items():
sheet.pack_forget() # Hide all tables
selected_table_name = self.table_listbox.get(selection[0])
self.tables[selected_table_name].pack(expand=True, fill='both')
def save_data(self, table_name):
"""Save current data of a table to a file."""
data = self.tables[table_name].get_sheet_data()
with open(os.path.join(self.save_file_dir, f"{table_name}.json"), 'w') as file:
json.dump(data, file)
print(f"Data for {table_name} saved successfully.")
if __name__ == "__main__":
root = tk.Tk()
app = TableApp(root)
root.mainloop()
Explanation
Sidebar Creation: A sidebar is created using a tkinter.Frame, which houses a button for creating new tables and a Listbox to display the available tables.
New Table Button: Clicking this button creates a new table. These tables are dynamically added to the tables dictionary, and an entry is added to the Listbox.
Listbox Selection: Selecting a table in the Listbox will display that table in the table frame, hiding others. This is managed by binding the ListboxSelect event to the load_selected_table method.
Persistence: Each table's data is saved in a JSON file inside a "tables" directory, with a unique filename based on the table name. The files are loaded when the application starts, making all previously created tables available.
Save-on-Change: Similar to before, each table saves its data automatically when a cell is changed, ensuring data permanence after every modification.
This setup allows you to manage multiple tables within a single application with a simple interface for creating and switching between them.
import tkinter as tk
from tksheet import Sheet
import json
import os
class TableApp:
def __init__(self, root):
self.root = root
self.root.title("Table Editor with Sidebar")
sidebar_bg_color = "#F7F8FC"
# Create main layout frames
self.sidebar = tk.Frame(root, width=200, bg=sidebar_bg_color, bd=0, relief='flat')
self.sidebar.pack(expand=False, fill='y', side='left', anchor='nw')
self.table_frame = tk.Frame(root)
self.table_frame.pack(expand=True, fill='both', side='right')
# Sidebar components
self.new_table_button = tk.Button(self.sidebar, text="New Table", command=self.create_new_table, bg=sidebar_bg_color, borderwidth=0, highlightthickness=0, relief='flat')
self.new_table_button.pack(padx=10, pady=10, fill='x')
self.table_listbox = tk.Listbox(self.sidebar, bg=sidebar_bg_color, borderwidth=0, highlightthickness=0, relief='flat', selectbackground='gray')
self.table_listbox.pack(expand=True, fill='both', padx=10, pady=10)
self.table_listbox.bind('<<ListboxSelect>>', self.load_selected_table)
self.save_file_dir = "tables"
self.tables = {} # Dictionary to hold table names and Sheet objects
if not os.path.exists(self.save_file_dir):
os.makedirs(self.save_file_dir)
self.load_tables()
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.tables[table_name] = Sheet(self.table_frame, data=[["" for _ in range(5)] for _ in range(10)])
self.tables[table_name].enable_bindings()
self.tables[table_name].extra_bindings([
("end_edit_cell", lambda event, table_name=table_name: self.save_data(table_name)),
])
self.tables[table_name].pack_forget() # Initially, hide the new table
self.table_listbox.insert('end', table_name)
self.table_listbox.select_set('end')
self.load_selected_table()
def load_tables(self):
"""Load existing tables from the directory."""
for filename in os.listdir(self.save_file_dir):
if filename.endswith(".json"):
table_name = filename[:-5] # Remove '.json' to get table name
self.table_listbox.insert('end', table_name)
self.tables[table_name] = Sheet(self.table_frame)
self.tables[table_name].enable_bindings()
self.tables[table_name].extra_bindings([
("end_edit_cell", lambda event, table_name=table_name: self.save_data(table_name)),
])
with open(os.path.join(self.save_file_dir, filename), 'r') as file:
data = json.load(file)
self.tables[table_name].set_sheet_data(data)
self.tables[table_name].pack_forget()
def load_selected_table(self, event=None):
"""Display the selected table and hide others."""
selection = self.table_listbox.curselection()
if selection:
for table_name, sheet in self.tables.items():
sheet.pack_forget() # Hide all tables
selected_table_name = self.table_listbox.get(selection[0])
self.tables[selected_table_name].pack(expand=True, fill='both')
def save_data(self, table_name):
"""Save current data of a table to a file."""
data = self.tables[table_name].get_sheet_data()
with open(os.path.join(self.save_file_dir, f"{table_name}.json"), 'w') as file:
json.dump(data, file)
print(f"Data for {table_name} saved successfully.")
if __name__ == "__main__":
root = tk.Tk()
app = TableApp(root)
root.mainloop()
Key Changes
Sidebar Background Color: The sidebar's background color is set to #F7F8FC by setting the bg parameter of the Frame to the desired color.
Flat Appearance: Set the bd (borderwidth) and relief to 0 and flat, respectively, for both the sidebar and widgets inside like the button and listbox. This gives a flat appearance.
Consistent Widget Styling: Ensure that the Listbox and Button widgets within the sidebar have their bg attribute set to match the sidebar, ensuring a consistent look. Additionally, borderwidth=0 and highlightthickness=0 are set for a flat look.
Inactive Selection Color: For aesthetics, you might want to change how selected items look in the Listbox by setting their active and inactive selections. You could use selectbackground to adjust the color of the selected item.
This code will create a sidebar with a flat, uniform color appearance that matches the specified hex color.
import tkinter as tk
from tksheet import Sheet
import json
import os
class TableApp:
def __init__(self, root):
self.root = root
self.root.title("Table Editor with Sidebar")
self.root.geometry("600x600") # Set window size to 600x600
sidebar_bg_color = "#F7F8FC"
# Create main layout frames
self.sidebar = tk.Frame(root, width=200, bg=sidebar_bg_color, bd=0, relief='flat')
self.sidebar.pack(expand=False, fill='y', side='left', anchor='nw')
self.table_frame = tk.Frame(root)
self.table_frame.pack(expand=True, fill='both', side='right')
# Sidebar components
self.new_table_button = tk.Button(self.sidebar, text="New Table", command=self.create_new_table, bg=sidebar_bg_color, borderwidth=0, highlightthickness=0, relief='flat')
self.new_table_button.pack(padx=10, pady=10, fill='x')
self.table_listbox = tk.Listbox(self.sidebar, bg=sidebar_bg_color, borderwidth=0, highlightthickness=0, relief='flat', selectbackground='gray')
self.table_listbox.pack(expand=True, fill='both', padx=10, pady=10)
self.table_listbox.bind('<<ListboxSelect>>', self.load_selected_table)
self.save_file_dir = "tables"
self.tables = {} # Dictionary to hold table names and Sheet objects
if not os.path.exists(self.save_file_dir):
os.makedirs(self.save_file_dir)
self.load_tables()
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.tables[table_name] = Sheet(self.table_frame, data=[["" for _ in range(5)] for _ in range(10)])
self.tables[table_name].enable_bindings()
self.tables[table_name].extra_bindings([
("end_edit_cell", lambda event, table_name=table_name: self.save_data(table_name)),
])
self.tables[table_name].pack_forget() # Initially, hide the new table
self.table_listbox.insert('end', table_name)
self.table_listbox.select_set('end')
self.load_selected_table()
def load_tables(self):
"""Load existing tables from the directory."""
for filename in os.listdir(self.save_file_dir):
if filename.endswith(".json"):
table_name = filename[:-5] # Remove '.json' to get table name
self.table_listbox.insert('end', table_name)
self.tables[table_name] = Sheet(self.table_frame)
self.tables[table_name].enable_bindings()
self.tables[table_name].extra_bindings([
("end_edit_cell", lambda event, table_name=table_name: self.save_data(table_name)),
])
with open(os.path.join(self.save_file_dir, filename), 'r') as file:
data = json.load(file)
self.tables[table_name].set_sheet_data(data)
self.tables[table_name].pack_forget()
def load_selected_table(self, event=None):
"""Display the selected table and hide others."""
selection = self.table_listbox.curselection()
if selection:
for table_name, sheet in self.tables.items():
sheet.pack_forget() # Hide all tables
selected_table_name = self.table_listbox.get(selection[0])
self.tables[selected_table_name].pack(expand=True, fill='both')
def save_data(self, table_name):
"""Save current data of a table to a file."""
data = self.tables[table_name].get_sheet_data()
with open(os.path.join(self.save_file_dir, f"{table_name}.json"), 'w') as file:
json.dump(data, file)
print(f"Data for {table_name} saved successfully.")
def set_dpi_awareness():
"""Enable DPI awareness to ensure high DPI settings are supported."""
try:
import ctypes
awareness = ctypes.c_int()
error_code = ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception as e:
print(f"Error setting DPI awareness: {e}")
if __name__ == "__main__":
set_dpi_awareness() # Enable DPI support
root = tk.Tk()
app = TableApp(root)
root.mainloop()
Key Additions
DPI Awareness: We added a function set_dpi_awareness to enable high DPI settings using the Windows API via ctypes. This code snippet calls SetProcessDpiAwareness(1), which requests "system DPI awareness." This is specific to Windows and may need to be adjusted for other operating systems.
Initial Window Size: We set the initial size of the window to 600x600 pixels using self.root.geometry("600x600").
Platform-Specific Considerations: The provided DPI code snippet is specific to Windows and may not affect applications on macOS or Linux. If you are targeting such environments, additional platform-specific methods might be necessary.
These modifications should ensure the application correctly supports high DPI displays and starts with the specified window size.
import tkinter as tk
from tksheet import Sheet
import json
import os
class TableApp:
def __init__(self, root):
self.root = root
self.root.title("Table Editor with Sidebar")
self.root.geometry("600x600") # Set window size to 600x600
sidebar_bg_color = "#F7F8FC"
# Create main layout frames
self.sidebar = tk.Frame(root, width=200, bg=sidebar_bg_color, bd=0, relief='flat')
self.sidebar.pack(expand=False, fill='y', side='left', anchor='nw')
self.table_frame = tk.Frame(root)
self.table_frame.pack(expand=True, fill='both', side='right')
# Sidebar components
self.new_table_button = tk.Button(self.sidebar, text="New Table", command=self.create_new_table,
bg=sidebar_bg_color, borderwidth=0, highlightthickness=0, relief='flat')
self.new_table_button.pack(padx=10, pady=10, fill='x')
self.table_listbox = tk.Listbox(self.sidebar, bg=sidebar_bg_color, borderwidth=0, highlightthickness=0,
relief='flat', selectbackground='gray')
self.table_listbox.pack(expand=True, fill='both', padx=10, pady=10)
self.table_listbox.bind('<<ListboxSelect>>', self.load_selected_table)
# Filter components
self.filter_label = tk.Label(self.sidebar, text="Filter:",
bg=sidebar_bg_color, anchor="w")
self.filter_label.pack(padx=10, pady=(10, 0), fill='x')
self.filter_entry = tk.Entry(self.sidebar)
self.filter_entry.pack(padx=10, pady=5, fill='x')
self.filter_button = tk.Button(self.sidebar, text="Apply Filter", command=self.apply_filter,
bg=sidebar_bg_color, borderwidth=0, highlightthickness=0, relief='flat')
self.filter_button.pack(padx=10, pady=5, fill='x')
self.save_file_dir = "tables"
self.tables = {} # Dictionary to hold table names and Sheet objects
self.original_data = {} # Dictionary to store the original data for each table
if not os.path.exists(self.save_file_dir):
os.makedirs(self.save_file_dir)
self.load_tables()
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.tables[table_name] = Sheet(self.table_frame, data=[["" for _ in range(5)] for _ in range(10)])
self.tables[table_name].enable_bindings()
self.tables[table_name].extra_bindings([
("end_edit_cell", lambda event, table_name=table_name: self.save_data(table_name)),
])
self.tables[table_name].pack_forget() # Initially, hide the new table
self.original_data[table_name] = self.tables[table_name].get_sheet_data()
self.table_listbox.insert('end', table_name)
self.table_listbox.select_set('end')
self.load_selected_table()
def load_tables(self):
"""Load existing tables from the directory."""
for filename in os.listdir(self.save_file_dir):
if filename.endswith(".json"):
table_name = filename[:-5] # Remove '.json' to get table name
self.table_listbox.insert('end', table_name)
self.tables[table_name] = Sheet(self.table_frame)
self.tables[table_name].enable_bindings()
self.tables[table_name].extra_bindings([
("end_edit_cell", lambda event, table_name=table_name: self.save_data(table_name)),
])
with open(os.path.join(self.save_file_dir, filename), 'r') as file:
data = json.load(file)
self.tables[table_name].set_sheet_data(data)
self.original_data[table_name] = data
self.tables[table_name].pack_forget()
def load_selected_table(self, event=None):
"""Display the selected table and hide others."""
selection = self.table_listbox.curselection()
if selection:
for table_name, sheet in self.tables.items():
sheet.pack_forget() # Hide all tables
selected_table_name = self.table_listbox.get(selection[0])
self.tables[selected_table_name].pack(expand=True, fill='both')
def save_data(self, table_name):
"""Save current data of a table to a file."""
data = self.tables[table_name].get_sheet_data()
with open(os.path.join(self.save_file_dir, f"{table_name}.json"), '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."""
term = self.filter_entry.get().lower()
selection = self.table_listbox.curselection()
if selection:
table_name = self.table_listbox.get(selection[0])
original_data = self.original_data[table_name]
filtered_data = [
row for row in original_data if any(term in str(cell).lower() for cell in row)
]
# Update the sheet data with the filtered data
self.tables[table_name].set_sheet_data(filtered_data)
def set_dpi_awareness():
"""Enable DPI awareness to ensure high DPI settings are supported."""
try:
import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception as e:
print(f"Error setting DPI awareness: {e}")
if __name__ == "__main__":
set_dpi_awareness() # Enable DPI support
root = tk.Tk()
app = TableApp(root)
root.mainloop()
Explanation
Filter UI Components: We're adding a Label, Entry, and Button to the sidebar to allow the user to input a search term and apply the filter.
Original Data Storage: We're using a dictionary original_data to store the initial data of each table to easily reset or reapply filters.
Filter Logic: The apply_filter() method retrieves the search term, checks which table is currently selected, and filters the rows of that table based on whether the search term is present in any cell of a row.
Data Setting: After filtering the rows, the method updates the Sheet widget to reflect the filtered data, showing only matching rows.
This setup allows the user to filter data rows interactively using a search term, enhancing data exploration in the application.
import tkinter as tk
from tksheet import Sheet
import json
import os
class TableApp:
def __init__(self, root):
self.root = root
self.root.title("Table Editor with Sidebar")
self.root.geometry("600x600") # Set window size to 600x600
sidebar_bg_color = "#F7F8FC"
# Create main layout frames
self.sidebar = tk.Frame(root, width=200, bg=sidebar_bg_color, bd=0, relief='flat')
self.sidebar.pack(expand=False, fill='y', side='left', anchor='nw')
self.main_frame = tk.Frame(root)
self.main_frame.pack(expand=True, fill='both', side='right')
# Header for filters
self.header_frame = tk.Frame(self.main_frame, height=50, bg=sidebar_bg_color)
self.header_frame.pack(fill='x')
# Filter components in the header
self.filter_label = tk.Label(self.header_frame, text="Filter:", bg=sidebar_bg_color, anchor="w")
self.filter_label.pack(side='left', padx=5, pady=10)
self.filter_entry = tk.Entry(self.header_frame)
self.filter_entry.pack(side='left', padx=5, pady=10)
self.filter_button = tk.Button(self.header_frame, text="Apply Filter", command=self.apply_filter,
bg=sidebar_bg_color, borderwidth=0, highlightthickness=0, relief='flat')
self.filter_button.pack(side='left', padx=5, pady=10)
# Frame for the table itself
self.table_frame = tk.Frame(self.main_frame)
self.table_frame.pack(expand=True, fill='both')
# Sidebar components
self.new_table_button = tk.Button(self.sidebar, text="New Table", command=self.create_new_table,
bg=sidebar_bg_color, borderwidth=0, highlightthickness=0, relief='flat')
self.new_table_button.pack(padx=10, pady=10, fill='x')
self.table_listbox = tk.Listbox(self.sidebar, bg=sidebar_bg_color, borderwidth=0, highlightthickness=0,
relief='flat', selectbackground='gray')
self.table_listbox.pack(expand=True, fill='both', padx=10, pady=10)
self.table_listbox.bind('<<ListboxSelect>>', self.load_selected_table)
self.save_file_dir = "tables"
self.tables = {} # Dictionary to hold table names and Sheet objects
self.original_data = {} # Dictionary to store the original data for each table
if not os.path.exists(self.save_file_dir):
os.makedirs(self.save_file_dir)
self.load_tables()
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.tables[table_name] = Sheet(self.table_frame, data=[["" for _ in range(5)] for _ in range(10)])
self.tables[table_name].enable_bindings()
self.tables[table_name].extra_bindings([
("end_edit_cell", lambda event, table_name=table_name: self.save_data(table_name)),
])
self.tables[table_name].pack_forget() # Initially, hide the new table
self.original_data[table_name] = self.tables[table_name].get_sheet_data()
self.table_listbox.insert('end', table_name)
self.table_listbox.select_set('end')
self.load_selected_table()
def load_tables(self):
"""Load existing tables from the directory."""
for filename in os.listdir(self.save_file_dir):
if filename.endswith(".json"):
table_name = filename[:-5] # Remove '.json' to get table name
self.table_listbox.insert('end', table_name)
self.tables[table_name] = Sheet(self.table_frame)
self.tables[table_name].enable_bindings()
self.tables[table_name].extra_bindings([
("end_edit_cell", lambda event, table_name=table_name: self.save_data(table_name)),
])
with open(os.path.join(self.save_file_dir, filename), 'r') as file:
data = json.load(file)
self.tables[table_name].set_sheet_data(data)
self.original_data[table_name] = data
self.tables[table_name].pack_forget()
def load_selected_table(self, event=None):
"""Display the selected table and hide others."""
selection = self.table_listbox.curselection()
if selection:
for table_name, sheet in self.tables.items():
sheet.pack_forget() # Hide all tables
selected_table_name = self.table_listbox.get(selection[0])
self.tables[selected_table_name].pack(expand=True, fill='both')
def save_data(self, table_name):
"""Save current data of a table to a file."""
data = self.tables[table_name].get_sheet_data()
with open(os.path.join(self.save_file_dir, f"{table_name}.json"), '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."""
term = self.filter_entry.get().lower()
selection = self.table_listbox.curselection()
if selection:
table_name = self.table_listbox.get(selection[0])
original_data = self.original_data[table_name]
filtered_data = [
row for row in original_data if any(term in str(cell).lower() for cell in row)
]
# Update the sheet data with the filtered data
self.tables[table_name].set_sheet_data(filtered_data)
def set_dpi_awareness():
"""Enable DPI awareness to ensure high DPI settings are supported."""
try:
import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception as e:
print(f"Error setting DPI awareness: {e}")
if __name__ == "__main__":
set_dpi_awareness() # Enable DPI support
root = tk.Tk()
app = TableApp(root)
root.mainloop()
Explanation
Main Layout: A new Frame (header_frame) has been added within the main_frame. This frame serves as a header above the table area (table_frame) and is packed with fill='x' to span the width of the main frame without interfering with the sidebar.
Filter Components: The filter components - label, entry, and button have been moved to the new header frame. This keeps the sidebar for navigation-related components, while the header handles table-specific filtering actions.
Adjustments: These UI elements are packed using side='left' to place them neatly in a row within the header.
This layout provides a clear separation between the sidebar for table navigation and the header for table-specific controls, enhancing the user's ability to interact with the table data.