Creating tree controls and adding items

A tree control is an instance of the class wx.TreeCtrl. Figure 15.1 displays a sample tree control.

Listing 15.1 shows the code used to generate that example. Notice that the tree is driven by an external structure stored in a file called We won't print that file here, but it is available at the book's web site. It consists of a nested list structure of the wxPython class hierarchy, a convenient data set for a tree control. Some of the mechanisms in this sample are discussed later in this chapter.

Wxpython Tree Control Clear Focused Item
Figure 15.1 A basic tree control example

Listing 15.1 Sample code for the tree example import wx import data class TestFrame(wx.Frame):

wx.Frame._init_(self, None, title="simple tree", size=(4 00,500)) self.tree = wx.TreeCtrl(self) root = self.tree.AddRoot("wx.Object") self.AddTreeNodes(root, data.tree)

Creating the tree <— Adding a root node <~| Adding nodes from the data set self.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.OnItemExpanded, <—i D. .. •

1 Binding some interesting events self.tree)

self.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.OnItemCollapsed, self.tree)

self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, self.tree)

self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivated, self.tree)

self.tree.Expand(root) <—i r .. .. r . , , ^ | Expanding the first level def AddTreeNodes(self, parentItem, items): <1— Building the tree nodes for item in items:

self.tree.AppendItem(parentItem, item) else:

newItem = self.tree.AppendItem(parentItem, item[0]) self.AddTreeNodes(newItem, item[1])

def GetItemText(self, item): if item:

return self.tree.GetItemText(item) else:

return ""

def OnItemExpanded(self, evt):

print "OnItemExpanded: ", self.GetItemText(evt.GetItem())

def OnItemCollapsed(self, evt):

print "OnItemCollapsed:", self.GetItemText(evt.GetItem())

def OnSelChanged(self, evt):

print "OnSelChanged: ", self.GetItemText(evt.GetItem())

def OnActivated(self, evt):

print "OnActivated: ", self.GetItemText(evt.GetItem())

app = wx.PySimpleApp(redirect=True)

frame = TestFrame()



The following constructor for wx.TreeCtrl is typical of the wxPython widget constructors.

wx.TreeControl(parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.TR_HAS_BUTTONS, validator=wx.DefaultValidator, name="treeCtrl")

The parameters are similar to the generic wx.Window object. The constructor provides you with an empty tree with no elements.

Was this article helpful?

0 0


  • kimmo
    How do you make a simple tree in wxpython custom tree?
    11 months ago

Post a comment