The wxPython GUI toolkit comes with many widgets. A common control is a tree widget. wxPython has several different tree widgets, including the regular wx.TreeCtrl, the newer DVC_TreeCtrl and the pure Python variants, CustomTreeCtrl and HyperTreeList. In this article, we will focus on the regular wx.TreeCtrl and learn the basics of how to create and use one.
Creating a Simple Tree
Creating a TreeCtrl is actually quite easy. The wxPython demo has a fairly complex example, so I wasn’t able to use it here. Instead I ended up taking the demo example and stripping it down as much as I could. Here’s the result:
import wx class MyTree(wx.TreeCtrl): def __init__(self, parent, id, pos, size, style): wx.TreeCtrl.__init__(self, parent, id, pos, size, style) class TreePanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.tree = MyTree(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TR_HAS_BUTTONS) self.root = self.tree.AddRoot('Something goes here') self.tree.SetPyData(self.root, ('key', 'value')) os = self.tree.AppendItem(self.root, 'Operating Systems') self.tree.Expand(self.root) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.tree, 0, wx.EXPAND) self.SetSizer(sizer) class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, parent=None, title='TreeCtrl Demo') panel = TreePanel(self) self.Show() if __name__ == '__main__': app = wx.App(redirect=False) frame = MainFrame() app.MainLoop()
In this example, we create a subclass of wx.TreeCtrl that doesn’t do anything. Then we create a panel subclass where we instantiate the tree and add a root and sub-item. Finally we create the frame that holds the panel and run the application. You should end up with something that looks similar to the following:
This is a pretty boring example, so let’s make something a bit more interesting. Continue reading wxPython: Learning about TreeCtrls