Tkinter Treeview搜索不会在搜索子级时最大化

时间:2019-06-15 15:26:27

标签: python-3.x search tkinter treeview

#当我在Tkinter Treeview中搜索3个字符的关键字时,搜索了#children的孩子,但是孩子级别没有最大化,但是当手动#maximized时,孩子的突出显示效果很好。另外,搜索的关键字不会#scroll窗口。有办法吗?请帮忙。

Search when scrolled manually and maximized the level


def search(self, item=''):
    search_pattern = str(self.searchText.get())
    if len(search_pattern) < 3:
        return

    children = self.tree.get_children(item)
    for child in children:
        value_list = self.tree.item(child)["values"]
        #print(value_list)
        for i in range(len(value_list)):
            if type(value_list[0]) != int:
                if value_list[0].isprintable():
                    #print(value_list[i],'printable')
                    #if value_list[0].lower().startswith(search_pattern.lower()):
                    if value_list[0].lower().find(search_pattern.lower()) != -1:
                        self.tree.selection_set(child)
                    else:
                        res = search(self,item=child)                
        search(self,item=child)


def search_box(root):

    root.searchText = StringVar()                                       
    root.search_input = ttk.Entry(root, textvariable = root.searchText, justify = LEFT)
    root.search_input.grid(column = 0, row = 0, padx=60, pady=5, sticky='NW', rowspan=2)
    print(root.search_input)
    print(root.searchText)

    root.searchText.trace_variable("w",lambda x,y,z: search(root))      # 
    Callback if stringvar is updated

    root.bind("<Return>", lambda x: hideEntry(root,x))
    root.bind("<Escape>", lambda x: hideEntry(root,x))

1 个答案:

答案 0 :(得分:0)

要展开分支,可以致电tree.item(iid, open=True)

要滚动到搜索完成的位置,可以使用tree.see(iid)

在您的search方法中将两者结合:

def search(self, item=''):
    search_pattern = str(self.searchText.get())
    if len(search_pattern) < 3:
        return

    children = self.tree.get_children(item)
    for child in children:
        value_list = self.tree.item(child)["values"]
        for i in range(len(value_list)):
            if type(value_list[0]) != int:
                if value_list[0].isprintable():
                    if value_list[0].lower().find(search_pattern.lower()) != -1:
                        self.tree.item(item,open=True)
                        self.tree.selection_set(child)
                        self.tree.see(child)
                    else:
                        res = search(self,item=child)                
        search(self,item=child)

您可以阅读有关树视图here的文档。