import tkinter as tk
from tkinter import ttk
import pandas as pd
data_list = [
{'id':1,'name': '苹果', 'price': 6.5,'tag':'水果'},
{'id':2,'name': '香蕉', 'price': 2.5,'tag':'水果'},
{'id':3,'name': '葡萄', 'price': 8.5,'tag':'水果'},
{'id':4,'name': '橘子', 'price': 4.5,'tag':'水果'},
]
df = pd.DataFrame(data_list)
app = tk.Tk()
app.title("商品数据表")
name_label = tk.Label(app, text="关键词")
name_label.grid(row=1, column=0, pady=10)
search_var = tk.StringVar()
search_entry = tk.Entry(app, textvariable=search_var,width=40)
search_entry.grid(row=1, column=1)
def search():
keyword = search_var.get()
if keyword:
result = df[df.astype(str).apply(lambda x: x.str.contains(keyword, case=False)).any(axis=1)]
update_table(result)
else:
update_table(df)
search_button = tk.Button(app, text="搜索", command=search)
search_button.grid(row=1, column=2, padx=10)
tree = ttk.Treeview(app, columns=list(df.columns), show="headings")
columns_cn = {'id': '序号','name': '商品', 'price': '价格','tag':'类别'}
for col in df.columns:
tree.heading(col, text=columns_cn[col])
tree.column(col, width=100, anchor="center")
for i, row in df.iterrows():
tree.insert("", "end", values=list(row))
def update_table(data):
tree.delete(*tree.get_children())
for i, row in data.iterrows():
tree.insert("", "end", values=list(row))
tree.grid(row=2, columnspan=4)
app.mainloop()
效果图如下:
这是一个简单的通过表格中的关键词 ,快速查找对应的商品,搜索+更新数据表的一个小的桌面应用。