要使用Python的SQLite和Tkinter库来创建一个具有增删改查(CRUD)功能的系统,你可以编写更复杂的逻辑来处理插入(Create)、读取(Retrieve)、更新(Update)和删除(Delete)操作。下面是一个扩展的示例代码,展示如何结合Tkinter和SQLite实现这些功能:
python
复制
import sqlite3
import tkinter as tk
from tkinter import messagebox
# 连接SQLite数据库
def connect_db():
conn = sqlite3.connect('example.db')
return conn
# 执行查询并返回结果
def execute_query(conn, query, params=()):
cursor = conn.cursor()
cursor.execute(query, params)
if query.lower().startswith('select'):
return cursor.fetchall()
else:
conn.commit()
return cursor.rowcount
# 显示查询结果
def show_results(results):
text_widget.delete('1.0', tk.END)
for row in results:
text_widget.insert(tk.END, str(row) + '\n')
# 创建数据表(如果尚未存在)
def create_table():
conn = connect_db()
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER
)
''')
conn.close()
# 插入数据
def insert_data():
name = name_entry.get()
age = age_entry.get()
if not name or not age:
messagebox.showerror("错误", "请输入完整的信息!")
return
query = "INSERT INTO users (name, age) VALUES (?, ?)"
conn = connect_db()
try:
row_count = execute_query(conn, query, (name, int(age)))
messagebox.showinfo("成功", f"插入了 {row_count} 行数据。")
except Exception as e:
messagebox.showerror("错误", str(e))
finally:
conn.close()
# 更新数据
def update_data():
id_ = id_entry.get()
name = name_entry.get()
age = age_entry.get()
if not id_ or not name or not age:
messagebox.showerror("错误", "请输入完整的信息!")
return
query = "UPDATE users SET name=?, age=? WHERE id=?"
conn = connect_db()
try:
row_count = execute_query(conn, query, (name, int(age), int(id_)))
messagebox.showinfo("成功", f"更新了 {row_count} 行数据。")
except Exception as e:
messagebox.showerror("错误", str(e))
finally:
conn.close()
# 删除数据
def delete_data():
id_ = id_entry.get()
if not id_:
messagebox.showerror("错误", "请输入要删除的数据的ID!")
return
query = "DELETE FROM users WHERE id=?"
conn = connect_db()
try:
row_count = execute_query(conn, query, (int(id_),))
messagebox.showinfo("成功", f"删除了 {row_count} 行数据。")
except Exception as e:
messagebox.showerror("错误", str(e))
finally:
conn.close()
# 查询数据
def query_data():
query = "SELECT * FROM users"
conn = connect_db()
try:
results = execute_query(conn, query)
show_results(results)
except Exception as e:
messagebox.showerror("错误", str(e))
finally:
conn.close()
# 创建Tkinter窗口
root = tk.Tk()
root.title("SQLite CRUD 系统")
# 创建插入数据的表单
name_label = tk.Label(root, text="Name:")
name_label.pack(side=tk.LEFT)
name_entry = tk.Entry(root)
name_entry.pack(side=tk.LEFT)
age_label = tk.Label(root, text="Age:")
age_label.pack(side=tk.LEFT)
age_entry = tk.Entry(root)
age_entry.pack(side=tk.LEFT)
insert_button = tk.Button(root, text="插入", command=insert_data)
insert_button.pack(side=tk.LEFT)
# 创建更新数据的表单
id_label = tk.Label(root, text="ID:")
id_label.pack(side=tk.LEFT)
id_entry = tk.Entry(root)
id_entry.pack(side=tk.LEFT)
update_button = tk.Button(root, text="更新", command=update_data)
update_button.pack(side=tk.LEFT)
# 创建删除数据的表单
delete_button = tk.Button(root, text="删除", command=delete_data)
delete_button.pack(side=tk.LEFT)
# 创建查询数据的表单
query_button = tk.Button(root, text="查询", command=query_data)
query_button.pack(side=tk.LEFT)
# 创建显示结果的文本框
text_widget = tk.Text(root, height=10, width=50)
text_widget.pack(pady=10)
# 创建数据表
create_table()
# 运行Tkinter事件循环
root.mainloop()
在这个示例中,我们创建了一个具有多个按钮和文本框的Tkinter窗口,用于插入、更新、删除和查询用户数据。每个按钮都绑定了一个回调函数,用于执行相应的数据库操作。我们还添加了一个文本框用于显示查询结果。
请注意,这个示例假设你已经有了一个名为example.db的SQLite数据库,并且该数据库中有一个名为users的表。如果表不存在,create_table函数会在第一次运行时创建它。
在实际应用中,你可能还需要添加更多的错误处理逻辑、输入验证以及更友好的用户界面。此外,对于大型应用程序,你可能还希望使用更复杂的数据库设计,以及更高级的Tkinter控件和布局。