首页 > 解决方案 > Python Tkinter Treeview 搜索所有条目

问题描述

我使用树视图来显示文件夹包含的所有项目。

我使用此功能创建所有条目:

def SUBS(path, parent):    
    for p in os.listdir(path):
        abspath = os.path.join(path, p)
        parent_element = tree.insert(parent, 'end', text=p, open=True)
        if os.path.isdir(abspath):
            SUBS(abspath, parent_element)

现在我想用这个功能搜索它:

def search(event, item=''): 
    children = tree.get_children(item)
    for child in children:
        text = tree.item(child, 'text')
        if text.startswith(entry.get()):
            tree.selection_set(child)

问题是搜索功能只搜索第一个“节点”。不是全部。那么我如何通过孩子的孩子进行搜索?他们怎么称呼?

标签: pythonpython-3.xsearchtkintertreeview

解决方案


为什么不在 SUBS 函数中使用递归?

def search(event, item=''): 
    children = tree.get_children(item)
    for child in children:
        text = tree.item(child, 'text')
        if text.startswith(entry.get()):
            tree.selection_set(child)
        search(None, item=child) # Use the function for all the children, their children, and so on..

推荐阅读