Python Tkinter: 使用 Treeview 查询特定区域的民警信息
import tkinter as tk
import tkinter.ttk as ttk
import pymysql as py
def zonghechaxunwindow():
window = ttk.Toplevel()
window.title('综合查询')
window.geometry('800x600')
def select1():
tree = ttk.Treeview(window)
tree['columns'] = ('id', 'name', 'gender', 'phone', 'address', 'remark')
tree.column('id', width=90)
tree.column('name', width=90)
tree.column('gender', width=90)
tree.column('phone', width=90)
tree.column('address', width=90)
tree.column('remark', width=90)
tree.heading('id', text='身份证号')
tree.heading('name', text='姓名')
tree.heading('gender', text='性别')
tree.heading('phone', text='联系电话')
tree.heading('address', text='家庭住址')
tree.heading('remark', text='职位')
tree.grid(column=0, row=1, sticky='NSEW')
conn = py.connect(host='localhost', user='root', password='houyushan1022', db='police')
cursor = conn.cursor()
cursor.execute("select * from person_info where 家庭住址='北京市朝阳区'" )
list_result = cursor.fetchall()
x = tree.get_children()
for item in x:
tree.delete(item)
for i in range(len(list_result)):
tree.insert('', i, text=str(i), values=(list_result[i][0], list_result[i][1], list_result[i][2], list_result[i][3], list_result[i][4], list_result[i][5]))
conn.commit()
conn.close()
select_button1 = tk.Button(window, bg='pink', text='查询家在北京朝阳区的民警', font=("微软雅黑 -20"), width=40, height=1, command=select1)
select_button1.place(x=10, y=370)
zonghechaxunwindow()
代码说明:
-
导入必要的库:
import tkinter as tk:导入 Tkinter 库,用于创建图形界面。import tkinter.ttk as ttk:导入 ttk 模块,用于创建主题化的控件,例如 Treeview。import pymysql as py:导入 pymysql 库,用于连接 MySQL 数据库。
-
创建窗口:
window = ttk.Toplevel():创建一个新的 Toplevel 窗口。window.title('综合查询'):设置窗口标题为 “综合查询”。window.geometry('800x600'):设置窗口大小为 800x600 像素。
-
创建 Treeview:
tree = ttk.Treeview(window):在窗口中创建一个 Treeview 控件。tree['columns'] = ('id', 'name', 'gender', 'phone', 'address', 'remark'):设置 Treeview 的列名。tree.column('id', width=90):设置列宽,这里将 “id” 列的宽度设置为 90 像素。tree.heading('id', text='身份证号'):设置列标题,这里将 “id” 列的标题设置为 “身份证号”。tree.grid(column=0, row=1, sticky='NSEW'):将 Treeview 控件放置在窗口中。
-
连接数据库和查询数据:
conn = py.connect(...):连接到 MySQL 数据库。cursor = conn.cursor():创建一个游标对象。cursor.execute("select * from person_info where 家庭住址='北京市朝阳区'" ):执行 SQL 查询语句,获取住在北京市朝阳区的民警信息。list_result = cursor.fetchall():将查询结果存储到列表中。tree.insert('', i, text=str(i), values=(list_result[i][0], ...)):将查询结果填充到 Treeview 中。
-
关闭数据库连接:
conn.commit():提交数据库事务。conn.close():关闭数据库连接。
-
创建查询按钮:
select_button1 = tk.Button(...):创建一个按钮,并设置按钮的属性,例如背景颜色、文本、字体等。select_button1.place(x=10, y=370):将按钮放置在窗口中。
运行代码:
运行代码后,将创建一个包含 Treeview 的窗口,其中展示了住在北京市朝阳区的民警信息。点击 “查询家在北京朝阳区的民警” 按钮,可以重新查询并更新 Treeview 的内容。
注意:
- 确保已安装 Tkinter、ttk 和 pymysql 库。
- 确保已创建名为 “police” 的数据库,并且数据库中包含名为 “person_info” 的表,该表包含民警信息。
- 修改代码中的数据库连接信息(主机地址、用户名、密码、数据库名称)以匹配您的实际环境。
- 修改查询语句以满足您的实际需求。
- 可以根据需要修改 Treeview 的列名、列宽、标题等。
- 可以根据需要添加更多查询按钮,实现不同的查询功能。
希望这能帮助您理解代码并实现您的需求!如果您有任何其他问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/ospD 著作权归作者所有。请勿转载和采集!