Search code examples
pythonwxpython

Get selected Item from wxtreeCtrl


How should you get the item selected in wxTreeCtrl? I bind the method to the activated item like this:

 self.tree.Bind (wx.EVT_TREE_ITEM_ACTIVATED, self.OnAdd, id=10)

And in the method OnAdd I try to get the item:

    def OnAdd(self, event):
        item =  event.GetItem()

But it gives error that event has no GetItem() method. Any idea?

UPDATE:

I had assigned a button event to process selected item. So that's why the event had not item attached to it..


Solution

  • You are binding the callback incorrectly. You currently do:

    self.Bind (wx.EVT_TREE_ITEM_ACTIVATED, self.OnAdd, id=10)
    

    But the 3rd parameter is the source; id is the 4th parameter. So, change it to this:

    self.tree = wx.TreeCtrl(self, size=(200,100)) # Or however you defined it
    self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnAdd, self.tree, id=10)
    

    This way, the event argument you will get in your OnAdd function will be the tree instance, which will have the GetItem method available.

    Full example:

    import wx
    
    class TreeExample(wx.Frame):
        def __init__(self):
            wx.Frame.__init__(self, None, title='Tree Example', size=(200, 130))
            self.tree = wx.TreeCtrl(self, size=(200, 100))
    
            root = self.tree.AddRoot('root')
            for item in ['item1', 'item2', 'item3']:
                self.tree.AppendItem(root, item)
            self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivated, self.tree)
            self.tree.Expand(root)
    
        def OnActivated(self, evt):
            print 'Double clicked on', self.tree.GetItemText(evt.GetItem())
    
    app = wx.PySimpleApp(None)
    TreeExample().Show()
    app.MainLoop()