开发者

wxPython: TreeCtrl: How can I get a tree item by name?

开发者 https://www.devze.com 2023-03-26 16:15 出处:网络
I am using wxPython and got a tree with some items. Now I need a function which give me the tree item object by name.

I am using wxPython and got a tree with some items. Now I need a function which give me the tree item object by name.

For example: item = self.GetItemByName("MyStories")

开发者_高级运维

I can not find such function in the documentation.

Does anyone has any ideas?


Here's one way to find the first tree item with a specific label:

def get_item_by_label(self, tree, search_text, root_item):
    item, cookie = tree.GetFirstChild(root_item)

    while item.IsOk():
        text = tree.GetItemText(item)
        if text.lower() == search_text.lower():
            return item
        if tree.ItemHasChildren(item):
            match = self.get_item_by_label(tree, search_text, item)
            if match.IsOk():
                return match
        item, cookie = tree.GetNextChild(root_item, cookie)

    return wx.TreeItemId()

result = get_item_by_label(tree, 'MyStories', tree.GetRootItem())
if result.IsOk():
    print('We have a match!')

But depending on what you're displaying in the tree, there's probably an easier way to handle it. The TreeCtrl already provides the tools to create references both ways between tree items and other objects as you fill the tree, and dict lookups are much faster and cleaner looking than what I just typed.


While robots.jpg answer will work but I find a much better solution is to track the ids in a dict like the following (hinted at by @robots.jpg & @Steven Sproat)

self.tree_item_ids = {}
root = self.tree.GetRootItem()
for obj in objs_to_add:
    tree_id = self.tree.AppendItem(root,obj.name)
    self.tree_item_ids[obj.name] = tree_id

and then later when you need to lookup the item for an object you can just grab the tree_id

tree_id = self.tree_item_ids[obj.name]
data = self.tree.GetPyData(tree_id)


You may also override TreeCtrl and change tree_ctrl_instance with self

def GetItemByName(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
0

精彩评论

暂无评论...
验证码 换一张
取 消