← Back to Home
💾 Bonus Part 6: Auto-Save Forms and User State in Tkinter – No Data Left Behind
📘 Overview
In this part, you’ll learn how to make your app remember user input between sessions by implementing:
-
Auto-save feature for form data
-
Restore form state when the app restarts
-
Use of JSON files to persist data
-
Good for apps like note-taking, to-do lists, or config dashboards
✅ Why Auto-Save?
-
Prevents data loss if the user closes the app accidentally
-
Makes your app feel more modern and user-friendly
-
Especially helpful for longer forms or repeat users
📦 What You’ll Use
-
json
– to store data -
Tkinter's
.get()
and.insert()
to read/write field values -
File I/O (
open()
) for saving/loading
✅ Example: Save and Load Form Data
import tkinter as tk
import json
import os
SAVE_FILE = "form_data.json"
class AutoSaveApp(tk.Tk):
def __init__(self):
super().__init__()
self.title("Auto-Save Form")
self.geometry("300x200")
tk.Label(self, text="Name:").pack()
self.name_entry = tk.Entry(self)
self.name_entry.pack()
tk.Label(self, text="Email:").pack()
self.email_entry = tk.Entry(self)
self.email_entry.pack()
self.protocol("WM_DELETE_WINDOW", self.on_close)
self.load_data()
def load_data(self):
if os.path.exists(SAVE_FILE):
with open(SAVE_FILE, "r") as f:
data = json.load(f)
self.name_entry.insert(0, data.get("name", ""))
self.email_entry.insert(0, data.get("email", ""))
def on_close(self):
data = {
"name": self.name_entry.get(),
"email": self.email_entry.get()
}
with open(SAVE_FILE, "w") as f:
json.dump(data, f)
self.destroy()
if __name__ == "__main__":
app = AutoSaveApp()
app.mainloop()
✅ How It Works
-
When the app closes, it writes the form data to
form_data.json
-
When the app starts, it checks for the file and restores the values
-
All done with standard JSON and basic file handling
🔐 Bonus: Encrypt the File (Optional)
For basic privacy:
import base64
# To save
encoded = base64.b64encode(json.dumps(data).encode()).decode()
with open(SAVE_FILE, "w") as f:
f.write(encoded)
# To load
with open(SAVE_FILE, "r") as f:
encoded = f.read()
data = json.loads(base64.b64decode(encoded.encode()).decode())
Note: This is not real encryption—use cryptography
or similar for secure apps.
💡 Recap
In this part, you learned how to:
-
Automatically save form fields on close
-
Restore user input on app restart
-
Use JSON for lightweight data persistence
🎉 You’ve now made your GUI more intelligent and user-friendly.
Would you like to move to Bonus Part 7: Building a Notification System (Popups & Toasts)
No comments:
Post a Comment