Quantcast
Channel: Python Archives - Mouse Vs Python
Viewing all articles
Browse latest Browse all 498

wxPython: Learning about TreeCtrls

$
0
0

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.


Creating an XML Viewer

Something that I’ve wanted to do for some time now is to create an XML editor with Python. To get started, I wrote some code a couple of weekends ago that could read XML into a TreeCtrl for viewing the tag elements. For this example, I will be using some sample XML I found on Microsoft’s MSDN website:

<?xml version="1.0"?>
<catalog>
    <book id="bk101">
        <author>Gambardella, Matthew</author>
        <title>XML Developer's Guide</title>
        <genre>Computer</genre>
        <price>44.95</price>
        <publish_date>2000-10-01</publish_date>
        <description>An in-depth look at creating applications 
        with XML.</description>
    </book>
    <book id="bk102">
        <author>Ralls, Kim</author>
        <title>Midnight Rain</title>
        <genre>Fantasy</genre>
        <price>5.95</price>
        <publish_date>2000-12-16</publish_date>
        <description>A former architect battles corporate zombies, 
        an evil sorceress, and her own childhood to become queen 
        of the world.</description>
    </book>
    <book id="bk103">
        <author>Corets, Eva</author>
        <title>Maeve Ascendant</title>
        <genre>Fantasy</genre>
        <price>5.95</price>
        <publish_date>2000-11-17</publish_date>
        <description>After the collapse of a nanotechnology 
        society in England, the young survivors lay the 
        foundation for a new society.</description>
    </book>
    <book id="bk104">
        <author>Corets, Eva</author>
        <title>Oberon's Legacy</title>
        <genre>Fantasy</genre>
        <price>5.95</price>
        <publish_date>2001-03-10</publish_date>
        <description>In post-apocalypse England, the mysterious 
        agent known only as Oberon helps to create a new life 
        for the inhabitants of London. Sequel to Maeve 
        Ascendant.</description>
    </book>
    <book id="bk105">
        <author>Corets, Eva</author>
        <title>The Sundered Grail</title>
        <genre>Fantasy</genre>
        <price>5.95</price>
        <publish_date>2001-09-10</publish_date>
        <description>The two daughters of Maeve, half-sisters, 
        battle one another for control of England. Sequel to 
        Oberon's Legacy.</description>
    </book>
    <book id="bk106">
        <author>Randall, Cynthia</author>
        <title>Lover Birds</title>
        <genre>Romance</genre>
        <price>4.95</price>
        <publish_date>2000-09-02</publish_date>
        <description>When Carla meets Paul at an ornithology 
        conference, tempers fly as feathers get ruffled.</description>
    </book>
    <book id="bk107">
        <author>Thurman, Paula</author>
        <title>Splish Splash</title>
        <genre>Romance</genre>
        <price>4.95</price>
        <publish_date>2000-11-02</publish_date>
        <description>A deep sea diver finds true love twenty 
        thousand leagues beneath the sea.</description>
    </book>
    <book id="bk108">
        <author>Knorr, Stefan</author>
        <title>Creepy Crawlies</title>
        <genre>Horror</genre>
        <price>4.95</price>
        <publish_date>2000-12-06</publish_date>
        <description>An anthology of horror stories about roaches,
        centipedes, scorpions  and other insects.</description>
    </book>
    <book id="bk109">
        <author>Kress, Peter</author>
        <title>Paradox Lost</title>
        <genre>Science Fiction</genre>
        <price>6.95</price>
        <publish_date>2000-11-02</publish_date>
        <description>After an inadvertant trip through a Heisenberg
        Uncertainty Device, James Salway discovers the problems 
        of being quantum.</description>
    </book>
    <book id="bk110">
        <author>O'Brien, Tim</author>
        <title>Microsoft .NET: The Programming Bible</title>
        <genre>Computer</genre>
        <price>36.95</price>
        <publish_date>2000-12-09</publish_date>
        <description>Microsoft's .NET initiative is explored in 
        detail in this deep programmer's reference.</description>
    </book>
    <book id="bk111">
        <author>O'Brien, Tim</author>
        <title>MSXML3: A Comprehensive Guide</title>
        <genre>Computer</genre>
        <price>36.95</price>
        <publish_date>2000-12-01</publish_date>
        <description>The Microsoft MSXML3 parser is covered in 
        detail, with attention to XML DOM interfaces, XSLT processing, 
        SAX and more.</description>
    </book>
    <book id="bk112">
        <author>Galos, Mike</author>
        <title>Visual Studio 7: A Comprehensive Guide</title>
        <genre>Computer</genre>
        <price>49.95</price>
        <publish_date>2001-04-16</publish_date>
        <description>Microsoft Visual Studio 7 is explored in depth,
        looking at how Visual Basic, Visual C++, C#, and ASP+ are 
        integrated into a comprehensive development 
        environment.</description>
    </book>
</catalog>

The first thing we need to decide is what Python XML parser we want to use. I personally like lxml the best, but Python’s own ElementTree is certainly a viable option and actually quite easy to switch too if you start out with lxml. But for this example, we will be using lxml. Let’s take a look:

import wx
 
from lxml import etree, objectify
 
 
class XmlTree(wx.TreeCtrl):
 
    def __init__(self, parent, id, pos, size, style):
        wx.TreeCtrl.__init__(self, parent, id, pos, size, style)
 
        try:
            with open(parent.xml_path) as f:
                xml = f.read()
        except IOError:
            print('Bad file')
            return
        except Exception as e:
            print('Really bad error')
            print(e)
            return
 
        self.xml_root = objectify.fromstring(xml)
 
        root = self.AddRoot(self.xml_root.tag)
        self.SetPyData(root, ('key', 'value'))        
 
        for top_level_item in self.xml_root.getchildren():
            child = self.AppendItem(root, top_level_item.tag)
            self.SetItemHasChildren(child)
            if top_level_item.attrib:
                self.SetPyData(child, top_level_item.attrib)
 
        self.Expand(root)
        self.Bind(wx.EVT_TREE_ITEM_EXPANDING, self.onItemExpanding)
 
    def onItemExpanding(self, event):
        item = event.GetItem()
        book_id = self.GetPyData(item)
 
        for top_level_item in self.xml_root.getchildren():
            if top_level_item.attrib == book_id:
                book = top_level_item
                self.SetPyData(item, top_level_item)                                
                self.add_book_elements(item, book)
                break
 
    def add_book_elements(self, item, book):
        for element in book.getchildren():
            child = self.AppendItem(item, element.tag)
            if element.getchildren():
                self.SetItemHasChildren(child)
 
            if element.attrib:
                self.SetPyData(child, element.attrib)  
 
 
class TreePanel(wx.Panel):
 
    def __init__(self, parent, xml_path):
        wx.Panel.__init__(self, parent)
        self.xml_path = xml_path
 
        self.tree = XmlTree(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,
                            wx.TR_HAS_BUTTONS)    
 
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.tree, 0, wx.EXPAND)
        self.SetSizer(sizer)
 
 
class MainFrame(wx.Frame):
 
    def __init__(self, xml_path):
        wx.Frame.__init__(self, parent=None, title='XML Editor')
        panel = TreePanel(self, xml_path)
        self.Show()
 
 
if __name__ == '__main__':
    xml_path = 'books.xml'
    app = wx.App(redirect=False)
    frame = MainFrame(xml_path)
    app.MainLoop()

The main change here is in the TreeCtrl subclass, although we had to make some small modifications in the other classes to pass in the XML file path. Let’s focus on the TreeCtrl class though. First we read the XML from the file and load it into lxml’s objectify module. At this point, we have an XML object that we can use to populate the TreeCtrl with data. So we add the root and then loop over the top-level children in the XML. For each top level element, we add an item to the root of the TreeCtrl. This is extremely basic as we should also be checking each element to see if it has children too. We don’t. Instead we just assume that it does and call the TreeCtrl’s SetItemHasChildren() method. This adds an arrow to the element to allow expanding of the element.

Lastly we expand the root and bind an event to EVT_TREE_ITEM_EXPANDING which will allow us to update the sub-elements when they get expanded. You can see how this is done in the onItemExpanding event handler and the add_book_elements() which is called by the event handler. Here we actually DO check the element to see if it has children using lxml’s getchildren(). If it does, then we call SetItemHasChildren(). The other thing I want to point out is all the calls to SetPyData(). The SetPyData() method is for saving data into the tree item. In this case, we are saving the XML element into the tree item itself, which we can get access to again via GetPyData(). This will be important if we want to add editing functionality to the GUI.


Other Odds and Ends

The wxPython demo also demonstrates some interesting tidbits. For example, it shows that you can add a wx.ImageList to your TreeCtrl. It also shows some of the other tree specific events you can bind to. Such as:

  • EVT_TREE_ITEM_COLLAPSED
  • EVT_TREE_SEL_CHANGED
  • EVT_TREE_BEGIN_LABEL_EDIT
  • EVT_TREE_END_LABEL_EDIT
  • EVT_TREE_ITEM_ACTIVATED

Of course, you can also bind to mouse events like EVT_LEFT_DCLICK and EVT_RIGHT_DOWN too.

If you’d like to make the tree elements editable, then you’ll need to pass the wx.TR_EDIT_LABELS style flag in when you instantiate the tree. Since my example is just a viewer, I didn’t feel the need to do that. There are some other style flags mentioned in the demo and in the documentation that you may also want to check out.


Wrapping Up

At this point, I think you should be able to get started using wxPython’s handy wx.TreeCtrl. It is quite powerful and easy to utilize. Should you find yourself needing to do something more custom, then I highly recommend checking out one of wxPython’s alternate tree controls, such as the CustomTreeCtrl or HyperTreeList.


Related Reading


Viewing all articles
Browse latest Browse all 498

Trending Articles