I have a python tkinter
application that contains a ttk.treeview
widget.
The widget displays a list of files found on a specific directory tree with a specific extension - this was trivial to build with tt.treeview
widget.
There is a request to enable "on-the-fly" filtering of the tree - e.g., the user types in an Entry
some string, and as he/she types, the tree removes elements that don't match the typed string so far.
I was exploring the Treeview
documentation, tried the detach
and reattach
methods but with no luck.
detach
indeed removes the non-matched elements from the tree, but if the user hit Backspace, I can no longer iterate correctly on the tree to restore those detached elements as get_children
method will not return them.
def filter_tree(self):
search_by = self.search_entry.get()
self.tree_detach_leaf_by_regex(self.current_loaded_folder, search_by, "")
def tree_detach_leaf_by_regex(self, root, regex, parent):
if self.treeview.get_children(root):
for child in self.treeview.get_children(root):
self.tree_detach_leaf_by_regex(child, regex, root)
else:
if not re.match(regex, self.treeview.item(root)["text"]):
self.elements_index_within_parent[root] = self.treeview.index(root)
self.elements_parents[parent] = 1
self.treeview.detach(root)
else:
self.treeview.reattach(root, parent, self.elements_index_within_parent[root])
Looking forward to read your advice.