You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Tkinter表格中创建关键词搜索栏?

给Tkinter CSV表格添加实时搜索功能

我已经用CSV数据创建了一个Tkinter表格UI,现在需要添加一个搜索栏,输入关键词后只显示包含该关键词的行,以下是我的初始代码:

from tkinter import *
import tkinter.ttk as ttk
import csv

root = Tk()
root.title("Python - Import CSV File To Tkinter Table")
width = 900
height = 600
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width/2) - (width/2)
y = (screen_height/2) - (height/2)
root.geometry("%dx%d+%d+%d" % (width, height, x, y))
root.resizable(0, 0)


TableMargin = Frame(root, width=500)
TableMargin.pack(side=TOP)
scrollbarx = Scrollbar(TableMargin, orient=HORIZONTAL)
scrollbary = Scrollbar(TableMargin, orient=VERTICAL)
tree = ttk.Treeview(TableMargin, columns=("Link", "Name", "Email"), height=400, selectmode="extended", yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
scrollbary.config(command=tree.yview)
scrollbary.pack(side=RIGHT, fill=Y)
scrollbarx.config(command=tree.xview)
scrollbarx.pack(side=BOTTOM, fill=X)
tree.heading('Link', text="Link", anchor=W)
tree.heading('Name', text="Name", anchor=W)
tree.heading('Email', text="Email", anchor=W)
tree.column('#0', stretch=NO, minwidth=0, width=0)
tree.column('#1', stretch=NO, minwidth=0, width=200)
tree.column('#2', stretch=NO, minwidth=0, width=200)
tree.column('#3', stretch=NO, minwidth=0, width=300)
tree.pack()

with open('output.csv') as f:
    # reader = csv.DictReader(f, delimiter=',')
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        if len(row) == 0:
            continue
        link: str = row[0]
        name: str = row[1]
        email: str = row[2]
        # specialty: str = row[3]
        tree.insert("", 0, values=(link, name, email))
        

#============================INITIALIZATION==============================
if __name__ == '__main__':
    root.mainloop()

修改后的完整代码(带搜索功能)

from tkinter import *
import tkinter.ttk as ttk
import csv

root = Tk()
root.title("Python - Import CSV File To Tkinter Table")
width = 900
height = 600
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width/2) - (width/2)
y = (screen_height/2) - (height/2)
root.geometry("%dx%d+%d+%d" % (width, height, x, y))
root.resizable(0, 0)

# 保存所有原始数据,避免重复读取CSV
all_data = []

# 搜索功能实现
def search_table():
    keyword = search_entry.get().lower()
    # 清空当前表格所有行
    for item in tree.get_children():
        tree.delete(item)
    # 遍历原始数据,匹配关键词的行重新插入
    for row in all_data:
        if len(row) == 0:
            continue
        # 检查任意字段是否包含关键词(不区分大小写)
        if keyword in row[0].lower() or keyword in row[1].lower() or keyword in row[2].lower():
            tree.insert("", 0, values=(row[0], row[1], row[2]))

# 添加搜索栏框架
SearchFrame = Frame(root)
SearchFrame.pack(side=TOP, fill=X, padx=10, pady=10)
search_label = Label(SearchFrame, text="搜索关键词:", font=('Arial', 10))
search_label.pack(side=LEFT)
search_entry = Entry(SearchFrame, width=50, font=('Arial', 10))
search_entry.pack(side=LEFT, padx=10)
# 绑定输入事件,实时搜索
search_entry.bind("<KeyRelease>", lambda event: search_table())
# 也可以添加搜索按钮,备用
search_btn = Button(SearchFrame, text="搜索", command=search_table, font=('Arial', 10))
search_btn.pack(side=LEFT)

TableMargin = Frame(root, width=500)
TableMargin.pack(side=TOP)
scrollbarx = Scrollbar(TableMargin, orient=HORIZONTAL)
scrollbary = Scrollbar(TableMargin, orient=VERTICAL)
tree = ttk.Treeview(TableMargin, columns=("Link", "Name", "Email"), height=400, selectmode="extended", yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
scrollbary.config(command=tree.yview)
scrollbary.pack(side=RIGHT, fill=Y)
scrollbarx.config(command=tree.xview)
scrollbarx.pack(side=BOTTOM, fill=X)
tree.heading('Link', text="Link", anchor=W)
tree.heading('Name', text="Name", anchor=W)
tree.heading('Email', text="Email", anchor=W)
tree.column('#0', stretch=NO, minwidth=0, width=0)
tree.column('#1', stretch=NO, minwidth=0, width=200)
tree.column('#2', stretch=NO, minwidth=0, width=200)
tree.column('#3', stretch=NO, minwidth=0, width=300)
tree.pack()

# 读取CSV并保存原始数据
with open('output.csv') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        all_data.append(row)
        if len(row) == 0:
            continue
        link: str = row[0]
        name: str = row[1]
        email: str = row[2]
        tree.insert("", 0, values=(link, name, email))

if __name__ == '__main__':
    root.mainloop()

关键说明

  1. 保存原始数据:新增all_data列表存储CSV的所有行,搜索时直接遍历这个列表,避免重复IO操作
  2. 搜索逻辑:search_table函数会清空当前表格,然后检查每一行的Link、Name、Email字段是否包含输入的关键词(不区分大小写,提升用户体验),匹配的行重新插入表格
  3. 实时搜索:绑定输入框的<KeyRelease>事件,用户输入或删除内容时自动触发搜索,无需点击按钮;同时保留了搜索按钮作为备用选项
  4. 兼容性:保留了原代码的所有布局和功能,仅添加搜索相关模块,不会破坏原有逻辑

内容的提问来源于stack exchange,提问作者CloudyTrees367

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 01:05:18