PythonGUI与数据库连接和操作
发布时间:2024-01-13 15:05:18
在Python中,可以使用不同的图形用户界面(GUI)库与数据库进行连接和操作。下面是使用tkinter和SQLite数据库的示例。
首先,确保已安装tkinter和SQLite的Python包。然后,创建一个GUI窗口,并在窗口中添加一些组件,例如标签、文本框和按钮。
import tkinter as tk
import sqlite3
def connect_to_database():
# 连接到SQLite数据库
conn = sqlite3.connect('example.db')
# 创建游标对象
cursor = conn.cursor()
# 创建表格
cursor.execute('''CREATE TABLE IF NOT EXISTS student
(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER);''')
# 提交更改
conn.commit()
# 关闭连接
conn.close()
def insert_data():
name = name_entry.get()
age = int(age_entry.get())
# 连接到数据库
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 执行插入语句
cursor.execute("INSERT INTO student (name, age) VALUES (?, ?)", (name, age))
# 提交更改
conn.commit()
# 关闭连接
conn.close()
def query_data():
# 连接到数据库
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 执行查询语句
cursor.execute("SELECT * FROM student")
# 获取查询结果
rows = cursor.fetchall()
# 输出结果
for row in rows:
print("ID: {}, Name: {}, Age: {}".format(row[0], row[1], row[2]))
# 关闭连接
conn.close()
# 创建GUI窗口
window = tk.Tk()
# 添加标签组件
name_label = tk.Label(window, text="Name:")
name_label.pack()
age_label = tk.Label(window, text="Age:")
age_label.pack()
# 添加文本框组件
name_entry = tk.Entry(window)
name_entry.pack()
age_entry = tk.Entry(window)
age_entry.pack()
# 添加按钮组件
connect_button = tk.Button(window, text="Connect to Database", command=connect_to_database)
connect_button.pack()
insert_button = tk.Button(window, text="Insert Data", command=insert_data)
insert_button.pack()
query_button = tk.Button(window, text="Query Data", command=query_data)
query_button.pack()
# 运行窗口事件循环
window.mainloop()
上面的代码首先导入tkinter和sqlite3库。然后,定义了三个函数:connect_to_database函数用于连接到SQLite数据库并创建一个表格,insert_data函数用于将数据插入表格中,query_data函数用于从表格中查询数据并输出。
接下来,创建一个GUI窗口,并在窗口中添加了一个标签、两个文本框和三个按钮。按钮的command参数指定了点击按钮时要执行的函数。
最后,调用window.mainloop()运行窗口事件循环,使程序保持运行状态。
通过运行上述代码,会显示一个GUI窗口,可以通过填写文本框并点击按钮来连接到数据库、插入数据和查询数据。所有的数据库操作都通过sqlite3库来实现。
