Python -在treeview中搜索和自动填充

5ktev3wc  于 2023-08-08  发布在  Python
关注(0)|答案(2)|浏览(90)

我在Treeview中搜索数据。


的数据
我的期望只是我想要的结果在treeview中显示。但它只出现在顶部,而其余的都还在那里。代码如下:

def search(i):
    # grab what was typed
    global typed_var
    typed = po1_entry.get().lower()
    for eachitem in my_tree.get_children():
        if typed in str(my_tree.item(eachitem)['values'][0]):
            typed_var = my_tree.item(eachitem)['values']
            my_tree.delete(eachitem)
            my_tree.insert("", 0, values=typed_var)

字符串
有什么办法可以解决这个问题吗?

ffscu2ro

ffscu2ro1#

假设该原则有效,则应该可以工作:

def search(i):
    # grab what was typed
    typed = po1_entry.get().lower()
    for eachitem in my_tree.get_children():
        search = my_tree.item(eachitem)['values']
        my_tree.delete(eachitem)
        if typed in search[0]:
            my_tree.insert("", 0, values=search)

字符串

8cdiaqws

8cdiaqws2#

看起来您希望在treeview中搜索数据,并只显示与搜索查询匹配的结果,同时删除其他行。但是,您提供的代码似乎有一个逻辑问题,导致只在treeview的顶部显示匹配的项。
问题就在这一行:

my_tree.insert("", 0, values=typed_var)

字符串
您将使用0作为第二个参数,它指定新项应插入的索引。这意味着新项目将始终插入到treeview的顶部(位置0)。相反,您应该根据搜索结果将其插入到适当的索引中。
下面是search函数的更新版本,应该可以按预期工作:

def search(i):
    # grab what was typed
    global typed_var
    typed = po1_entry.get().lower()
    
    # Clear existing items from the treeview
    my_tree.delete(*my_tree.get_children())
    
    # Insert only the matching items back into the treeview
    for eachitem in original_data:  # Use your original data source here
        if typed in str(eachitem[0]):  # Assuming eachitem is a list of values
            my_tree.insert("", "end", values=eachitem)

相关问题