Certainly! Below is a Python GUI application built using tksheet and Tkinter that allows you to create, edit, and manage tables with large amounts of data. The application features automatic saving to a JSON file whenever changes are made, ensuring your data is always up to date.
Features:
- Create and Edit Tables: Easily add or remove rows and columns, and edit cell contents.
- Automatic Saving: Changes are automatically saved to a JSON file (
data.json) to prevent data loss.
- Modern Python Features: Utilizes type hints, data classes, and the latest Python 3.12 capabilities for cleaner and more efficient code.
Requirements:
- Python 3.12
- tksheet library
Installation:
First, install the required tksheet library using pip:
pip install tksheet
Complete Code:
import json
import os
import tkinter as tk
from tkinter import filedialog, messagebox
from dataclasses import dataclass, field
from typing import List, Any
import threading
import time
import tksheet
DATA_FILE = "data.json"
AUTO_SAVE_INTERVAL = 5 # seconds
@dataclass
class TableData:
headers: List[str] = field(default_factory=lambda: ["Column 1", "Column 2"])
data: List[List[Any]] = field(default_factory=lambda: [["", ""]])
def to_dict(self) -> dict:
return {"headers": self.headers, "data": self.data}
@staticmethod
def from_dict(data: dict) -> "TableData":
return TableData(headers=data.get("headers", ["Column 1", "Column 2"]),
data=data.get("data", [["", ""]]))
class AutoSaveThread(threading.Thread):
def __init__(self, app: 'TableApp', interval: int = AUTO_SAVE_INTERVAL):
super().__init__(daemon=True)
self.app = app
self.interval = interval
self.running = True
def run(self):
while self.running:
time.sleep(self.interval)
self.app.save_data()
def stop(self):
self.running = False
class TableApp:
def __init__(self, root: tk.Tk):
self.root = root
self.root.title("TkSheet Table Editor")
self.table_data = self.load_data()
self.sheet = tksheet.Sheet(
self.root,
headers=self.table_data.headers,
data=self.table_data.data,
hide_row_index=True,
show_borders=True,
width=800,
height=600
)
self.sheet.enable_bindings(
("single_select", "column_select", "row_select",
"column_drag_and_drop", "row_drag_and_drop",
"arrowkeys", "right_click_popup_menu", "rc_select",
"rc_insert_row", "rc_delete_row", "rc_insert_column",
"rc_delete_column", "edit_cell")
)
self.sheet.grid(row=0, column=0, sticky="nsew")
# Configure grid weights
self.root.grid_rowconfigure(0, weight=1)
self.root.grid_columnconfigure(0, weight=1)
# Bind events to track changes
self.sheet.extra_bindings("end_edit_cell", self.on_cell_change)
self.sheet.extra_bindings("end_insert_row", self.on_data_change)
self.sheet.extra_bindings("end_delete_row", self.on_data_change)
self.sheet.extra_bindings("end_insert_column", self.on_data_change)
self.sheet.extra_bindings("end_delete_column", self.on_data_change)
# Start auto-save thread
self.auto_save_thread = AutoSaveThread(self)
self.auto_save_thread.start()
# Handle window closing
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
def load_data(self) -> TableData:
if os.path.exists(DATA_FILE):
try:
with open(DATA_FILE, "r", encoding="utf-8") as f:
data_dict = json.load(f)
return TableData.from_dict(data_dict)
except Exception as e:
messagebox.showerror("Error", f"Failed to load data: {e}")
return TableData()
def save_data(self):
try:
self.table_data.headers = self.sheet.headers
self.table_data.data = self.sheet.get_sheet_data()
with open(DATA_FILE, "w", encoding="utf-8") as f:
json.dump(self.table_data.to_dict(), f, indent=4)
print("Data saved.")
except Exception as e:
print(f"Failed to save data: {e}")
def on_cell_change(self, event: Any):
self.save_data()
def on_data_change(self, event: Any):
self.save_data()
def on_close(self):
self.auto_save_thread.stop()
self.save_data()
self.root.destroy()
def main():
root = tk.Tk()
app = TableApp(root)
root.mainloop()
if __name__ == "__main__":
main()
Explanation:
-
Data Handling with TableData Data Class:
- Utilizes a
@dataclass to manage table headers and data.
- Provides methods to convert to and from dictionaries for easy JSON serialization.
-
Auto-Save Functionality:
- Implements a separate
AutoSaveThread that periodically calls the save_data method every AUTO_SAVE_INTERVAL seconds.
- Ensures the GUI remains responsive by running the save operation in a background thread.
-
GUI with tksheet:
- Initializes a
tksheet.Sheet with headers and data loaded from data.json.
- Enables bindings for various interactions like selecting, editing, inserting, and deleting rows/columns.
- Listens to events such as
end_edit_cell, end_insert_row, etc., to trigger data saving.
-
Automatic Data Saving:
- The
save_data method updates the TableData instance with the current state of the sheet and writes it to data.json.
- Additionally, data is saved immediately upon any change in the table via event bindings.
-
Graceful Shutdown:
- When the window is closed, the auto-save thread is stopped, any final data is saved, and the application exits gracefully.
Running the Application:
-
Ensure Dependencies are Installed:
Make sure you have Python 3.12 and tksheet installed.
pip install tksheet
-
Save the Code:
Save the above code in a Python file, e.g., table_editor.py.
-
Run the Application:
Execute the script using Python.
python table_editor.py
-
Usage:
- Add Rows/Columns: Right-click on the sheet to access the context menu for inserting or deleting rows and columns.
- Edit Cells: Double-click on any cell to edit its content.
- Automatic Saving: All changes are automatically saved to
data.json every 5 seconds and immediately upon modifications.
Enhancements and Considerations:
- Data Validation: Implement data validation to ensure data integrity.
- Multiple Sheets: Extend functionality to handle multiple sheets/tables within the same application.
- Export Options: Add options to export data to different formats like CSV or Excel.
- Improved UI: Enhance the user interface with more features like search, filter, and sorting.
This application provides a solid foundation for managing large amounts of tabular data with ease. You can further customize and expand its functionalities based on your specific requirements.