Build a 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 automaticly.
Assistant
Certainly! Below is a comprehensive Python program using the tksheet library to create, edit, and automatically save large amounts of table data. This application allows users to interact with tables seamlessly and ensures that all changes are saved automatically to a CSV file.
Features:
Create and Edit Tables: Users can add/remove rows and columns and edit cell contents.
Automatic Saving: Changes are automatically saved to a CSV file at regular intervals and when the application is closed.
Load Existing Data: If a saved CSV file exists, it loads the data when the application starts.
User-Friendly Interface: Intuitive buttons for managing table structure.
Prerequisites:
Python 3.x installed on your system.
Install Required Libraries:
tksheet: For the spreadsheet-like widget.
tkinter: Usually comes pre-installed with Python.
You can install tksheet using pip if you haven't already:
bash
pip install tksheet
Complete Code:
python
import tkinter as tk
from tkinter import filedialog, messagebox
import tksheet
import csv
import os
class AutoSaveSheet(tk.Tk):
def __init__(self, filename='data.csv', save_interval=5000):
super().__init__()
self.title("AutoSave Table Editor")
self.geometry("800x600")
self.filename = filename
self.save_interval = save_interval # in milliseconds
# Create the sheet widget
self.sheet = tksheet.Sheet(self,
data=[],
headers=[],
show_toolbar=True,
show_statusbar=True,
toolbar_options={
'height': 25,
'bg': '#f0f0f0',
'font': ('Arial', 10)
})
self.sheet.enable_bindings((
"single_select",
"row_select",
"column_select",
"drag_select",
"edit_cell",
"arrowkeys",
"right_click_popup_menu",
"rc_insert_row",
"rc_delete_row",
"rc_insert_column",
"rc_delete_column",
"copy",
"cut",
"paste",
"undo",
"redo",
"drag_and_drop",
"select_all"
))
self.sheet.grid(row=0, column=0, sticky="nswe")
# Configure grid
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
# Load existing data if available
if os.path.exists(self.filename):
self.load_data()
else:
# Initialize with some default headers and empty data
self.sheet.headers(["Column {}".format(i+1) for i in range(5)])
self.sheet.set_sheet_data([["" for _ in range(5)] for _ in range(20)])
# Bind cell changes to trigger save
self.sheet.extra_bindings("cell_edit_end", [self.on_cell_edit])
# Set up automatic saving
self.after(self.save_interval, self.auto_save)
# Handle window closing to ensure data is saved
self.protocol("WM_DELETE_WINDOW", self.on_close)
def on_cell_edit(self, event):
"""Callback when a cell is edited."""
# You can add more sophisticated change handling here
self.schedule_save()
def schedule_save(self):
"""Schedules a save operation."""
# Reset the save timer
if hasattr(self, 'save_after_id'):
self.after_cancel(self.save_after_id)
self.save_after_id = self.after(1000, self.save_data) # Save after 1 second of inactivity
def auto_save(self):
"""Periodic save."""
self.save_data()
self.after(self.save_interval, self.auto_save)
def save_data(self):
"""Saves the current sheet data to a CSV file."""
headers = self.sheet.headers()
data = self.sheet.get_sheet_data(return_copy=True)
try:
with open(self.filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(headers)
writer.writerows(data)
print(f"Data saved to {self.filename}")
except Exception as e:
print(f"Error saving data: {e}")
def load_data(self):
"""Loads data from a CSV file into the sheet."""
try:
with open(self.filename, 'r', newline='', encoding='utf-8') as f:
reader = csv.reader(f)
all_data = list(reader)
if all_data:
headers = all_data[0]
data = all_data[1:] if len(all_data) > 1 else []
self.sheet.headers(headers)
self.sheet.set_sheet_data(data)
print(f"Data loaded from {self.filename}")
except Exception as e:
print(f"Error loading data: {e}")
def on_close(self):
"""Handles the window close event."""
self.save_data()
self.destroy()
if __name__ == "__main__":
app = AutoSaveSheet()
app.mainloop()
Explanation:
Imports:
tkinter and tksheet for GUI elements.
csv for reading and writing CSV files.
os for checking file existence.
AutoSaveSheet Class:
Initialization (__init__):
Sets up the main window with a title and size.
Initializes the tksheet.Sheet widget with toolbar and status bar.
Enables various bindings for user interactions like cell editing, row/column insertion, etc.
Loads existing data from a CSV file if it exists; otherwise, initializes with default headers and empty rows.
Binds the cell_edit_end event to handle post-edit actions.
Sets up an automatic save mechanism that triggers every save_interval milliseconds (default is 5000 ms or 5 seconds).
Ensures that data is saved when the window is closed.
Event Handlers:
on_cell_edit: Triggered after a cell is edited. Schedules a save operation after a short delay to prevent excessive saving.
schedule_save: Resets the save timer to avoid multiple saves in quick succession.
auto_save: Periodically saves data and reschedules itself.
save_data: Writes the current sheet data to a CSV file. It handles headers and data separately.
load_data: Reads data from a CSV file and populates the sheet.
on_close: Ensures that data is saved before the application closes.
Main Execution:
Creates an instance of AutoSaveSheet and starts the Tkinter main loop.
Usage:
Run the Program:
Save the above code to a file, e.g., autosave_sheet.py.
Execute the script using Python:
bash
python autosave_sheet.py
Interacting with the Table:
Editing Cells: Click on any cell to edit its contents.
Adding Rows/Columns: Right-click to bring up the context menu and choose to insert or delete rows and columns.
Saving: The application automatically saves changes every 5 seconds and after each cell edit, ensuring that your data isn't lost.
Loading Data: When you reopen the application, it will load the previously saved data from data.csv.
Customization:
Change Save Location: Modify the filename parameter when creating the AutoSaveSheet instance to change where data is saved.
Adjust Save Interval: Change the save_interval parameter (in milliseconds) to adjust how frequently the application auto-saves.
Enhancements:
Depending on your requirements, you might consider the following enhancements:
Different File Formats: Instead of CSV, you could save data in JSON or a database for better scalability.
Validation: Implement data validation to ensure that inputs meet certain criteria.
Styling: Customize the appearance of the sheet for better user experience.
Import/Export Options: Add buttons to manually import/export data in different formats.
Search and Filtering: Implement search functionality to navigate large datasets efficiently.
Conclusion
This program provides a robust foundation for managing large amounts of tabular data with automatic saving capabilities using tksheet in Tkinter. It ensures data integrity and offers flexibility for further customization based on your specific needs.
If you encounter any issues or have further questions, feel free to ask!