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

如何在包含tuple的List中搜索匹配指定字符串的元组?

Tkinter中实现Tuple列表的搜索并更新Treeview

问题分析

原代码的核心问题是直接判断字符串是否在tuple中的逻辑错误,因为tuple是容器对象,typed in item无法正确匹配tuple内的元素;另外原代码缺少Treeview的创建与更新逻辑,无法实现搜索结果的可视化更新。

修正后的完整代码

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.geometry("600x300")

# 原始数据
data = [
    ('SS Tubing, Primary Head Lower Transducer', 'ABC324232', 10.0), 
    ('Assy Tubing, L Head- Top Transducer', 'ABC093762', 20.0), 
    ('Assy Tubing, Lower Transducer-Accum Head', 'ABC099762', 13.0), 
    ('Assy Tubing ,Top Transducer- Vent Valve', 'ABC0911562', 23.0)
]

# 创建Treeview
tree = ttk.Treeview(root, columns=("Name", "PartNo", "Qty"), show="headings")
# 设置表头
tree.heading("Name", text="部件名称")
tree.heading("PartNo", text="部件编号")
tree.heading("Qty", text="数量")
# 设置列宽
tree.column("Name", width=300)
tree.column("PartNo", width=150)
tree.column("Qty", width=80)
tree.place(x=20, y=70)

# 初始化加载所有数据
def load_data(items):
    # 清空现有内容
    for item in tree.get_children():
        tree.delete(item)
    # 插入新数据
    for item in items:
        tree.insert("", tk.END, values=item)

load_data(data)

# 搜索逻辑实现
def searchBox_fun(e):
    typed = Search_box.get().strip().lower()  # 去除空格并转为小写,实现大小写不敏感搜索
    new_list = []
    for item in data:
        # 遍历tuple中的每个元素,转为字符串后检查是否包含搜索文本
        for element in item:
            if typed in str(element).lower():
                new_list.append(item)
                break  # 只要有一个元素匹配,就加入列表并跳出当前tuple的遍历
    # 更新Treeview
    load_data(new_list)

# 创建搜索框
Search_box = tk.Entry(root, font=("Helvetica", 12), width=40)
Search_box.place(x=60, y=30)
Search_box.bind("<KeyRelease>", searchBox_fun)

root.mainloop()

关键修改点

  • 移除了错误的from logging import root导入,避免命名冲突
  • 添加了Treeview组件的创建、表头设置与初始化加载逻辑
  • 修正搜索逻辑:遍历tuple的每个元素,将元素转为字符串后进行大小写不敏感的匹配
  • 实现了Treeview的清空与重新加载功能,确保搜索结果实时更新
  • 修复了原代码中new_list.append(item)的缩进错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:25:22