问题
How can I check if a certain root in a wx.TreeCtrl object has a certain child or not?
I am writing manual functions to update TreeCtrl every time a child is added by user.Is there a way to automate this?
回答1:
You might want to consider storing the data in some other easily-searchable structure, and using the TreeCtrl
just to display it. Otherwise, you can iterate over the children of a TreeCtrl
root item like this:
def item_exists(tree, match, root):
item, cookie = tree.GetFirstChild(root)
while item.IsOk():
if tree.GetItemText(item) == match:
return True
#if tree.ItemHasChildren(item):
# if item_exists(tree, match, item):
# return True
item, cookie = tree.GetNextChild(root, cookie)
return False
result = item_exists(tree, 'some text', tree.GetRootItem())
Uncommenting the commented lines will make it a recursive search.
回答2:
A nicer way to handle recursive tree traversal is to wrap it in a generator object, which you can then re-use to perform any operation you like on your tree nodes:
def walk_branches(tree,root):
""" a generator that recursively yields child nodes of a wx.TreeCtrl """
item, cookie = tree.GetFirstChild(root)
while item.IsOk():
yield item
if tree.ItemHasChildren(item):
walk_branches(tree,item)
item,cookie = tree.GetNextChild(root,cookie)
for node in walk_branches(my_tree,my_root):
# do stuff
回答3:
For searching by text without recursion :
def GetItemByText(self, search_text, tree_ctrl_instance):
retval = None
root_list = [tree_ctrl_instance.GetRootItem()]
for root_child in root_list:
item, cookie = tree_ctrl_instance.GetFirstChild(root_child)
while item.IsOk():
if tree_ctrl_instance.GetItemText(item) == search_text:
retval = item
break
if tree_ctrl_instance.ItemHasChildren(item):
root_list.append(item)
item, cookie = tree_ctrl_instance.GetNextChild(root_child, cookie)
return retval
来源:https://stackoverflow.com/questions/7919992/finding-certain-child-in-wxtreectrl-and-updating-treectrl-in-wxpython