1. Establishes database connectivity with SQLite.
Creates a
table, inserts records, and retrieves data from a database.
Displays the data in a GUI window using Tkinter. Threads the
database operation to keep the GUI responsive.
import sqlite3
import tkinter as tk
from tkinter import ttk
import threading
# Database setup
def setup_database():
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
c.execute('''INSERT INTO users (name, age) VALUES
('Alice', 30),
('Bob', 25),
('Charlie', 35)''')
conn.commit()
conn.close()
# Fetch data from the database
def fetch_data():
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('SELECT * FROM users')
rows = c.fetchall()
conn.close()
return rows
# Update the GUI with the fetched data
def update_gui(tree):
for i in tree.get_children():
tree.delete(i)
for row in fetch_data():
tree.insert('', tk.END, values=row)
# Threaded database fetch
def threaded_fetch(tree):
threading.Thread(target=lambda: update_gui(tree)).start()
# Main application window
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("SQLite and Tkinter Example")
self.geometry("400x300")
self.tree = ttk.Treeview(self, columns=('ID', 'Name', 'Age'), show='headings')
self.tree.heading('ID', text='ID')
self.tree.heading('Name', text='Name')
self.tree.heading('Age', text='Age')
self.tree.pack(expand=True, fill=tk.BOTH)
self.refresh_button = tk.Button(self, text="Refresh", command=lambda:
threaded_fetch(self.tree))
self.refresh_button.pack()
# Setup and run the application
if __name__ == "__main__":
setup_database()
app = App()
threaded_fetch(app.tree)
app.mainloop()