Connect Tkinter to SQLite – Save and Retrieve Data in Python GUI Apps

 

← Back to Home

🐍 Python UI Programming Series — Part 5: Connecting Tkinter GUI to a Database with SQLite


📘 Overview

So far, you've built interactive, styled, and multi-page GUI apps. Now it's time to make your apps persist data — that means saving and retrieving user input using a database.

In this part, you'll learn:

  • What is SQLite and why it's great for beginners

  • How to connect Tkinter to SQLite

  • Create a form that saves user input to the database

  • Display stored data in your app


🛢️ What is SQLite?

  • SQLite is a lightweight, file-based database engine.

  • It requires no server setup and is included with Python via the sqlite3 module.

  • Ideal for small to medium apps and local desktop use.


🧰 Setting Up the Database

✅ Create a Table for User Data

import sqlite3

# Connect (or create) database
conn = sqlite3.connect("users.db")

# Create a table
conn.execute('''
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    email TEXT NOT NULL
)
''')

conn.close()

You only need to run this once to set up the database.


🖥️ Tkinter Form to Save User Data

✅ Full Example: Data Entry + SQLite Save

import tkinter as tk
from tkinter import messagebox
import sqlite3

def save_to_db():
    name = entry_name.get()
    email = entry_email.get()
    if not name or not email:
        messagebox.showwarning("Input Error", "All fields are required!")
        return

    conn = sqlite3.connect("users.db")
    conn.execute("INSERT INTO users (name, email) VALUES (?, ?)", (name, email))
    conn.commit()
    conn.close()

    messagebox.showinfo("Success", "User saved!")
    entry_name.delete(0, tk.END)
    entry_email.delete(0, tk.END)

root = tk.Tk()
root.title("Save to Database")
root.geometry("300x200")

tk.Label(root, text="Name:").pack(pady=5)
entry_name = tk.Entry(root)
entry_name.pack()

tk.Label(root, text="Email:").pack(pady=5)
entry_email = tk.Entry(root)
entry_email.pack()

tk.Button(root, text="Save", command=save_to_db).pack(pady=15)

root.mainloop()

🎯 This app:

  • Takes user input

  • Validates it

  • Saves it to a local SQLite database

  • Shows a success message


📋 View Stored Data in Your App

You can also add a section to display saved users:

def show_users():
    conn = sqlite3.connect("users.db")
    cursor = conn.execute("SELECT name, email FROM users")
    data = cursor.fetchall()
    conn.close()

    text_output.delete("1.0", tk.END)
    for row in data:
        text_output.insert(tk.END, f"Name: {row[0]}, Email: {row[1]}\n")

tk.Button(root, text="Show Users", command=show_users).pack(pady=5)
text_output = tk.Text(root, height=5, width=30)
text_output.pack(pady=5)

📄 Now your app reads and displays data from the database!


💡 Recap

In this part, you’ve learned:

  • What SQLite is and how it works with Python

  • How to connect a Tkinter form to a SQLite database

  • How to store and display user data in a GUI


🚀 Coming Up in Part 6:

“Form Validation and Error Handling in Tkinter Apps”

  • Ensure only valid input is accepted

  • Display error messages cleanly

  • Prevent crashes with try-except blocks



No comments:

Post a Comment

Featured Post

Add Keyboard Shortcuts to Tkinter GUI – Python Hotkeys with Bind Examples

  ← Back to Home ⌨️ Bonus Part 5: Keyboard Shortcuts & Hotkeys in Tkinter – Boost App Productivity 📘 Overview Keyboard shortcuts ...

Popular Posts