Welcome, guest | Sign In | My Account | Store | Cart

IDLE, an integrated development environment for Python written in 100% Python using Tkinter, is included in Python 2.3 standard library as `idlelib'.

This recipie, domtree.py', is a simple example for usingidlelib.TreeWidget'. It is a simplistic DOM viewer.

Python, 51 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# domtree.py
# This is a simple example for idlelib.TreeWidget

# Written by Seo Sanghyeon
# Put into the public domain

from Tkinter import Tk, Canvas
from xml.dom.minidom import parseString
from idlelib.TreeWidget import TreeItem, TreeNode

class DomTreeItem(TreeItem):
    def __init__(self, node):
        self.node = node
    def GetText(self):
        node = self.node
        if node.nodeType == node.ELEMENT_NODE:
            return node.nodeName
        elif node.nodeType == node.TEXT_NODE:
            return node.nodeValue
    def IsExpandable(self):
        node = self.node
        return node.hasChildNodes()
    def GetSubList(self):
        parent = self.node
        children = parent.childNodes
        prelist = [DomTreeItem(node) for node in children]
        itemlist = [item for item in prelist if item.GetText().strip()]
        return itemlist

data = '''
<a>
 <b>
  <c>d</c>
  <c>e</c>
 </b>
 <b>
  <c>f</c>
 </b>
</a>
'''

root = Tk()
canvas = Canvas(root)
canvas.config(bg='white')
canvas.pack()
dom = parseString(data)
item = DomTreeItem(dom.documentElement)
node = TreeNode(canvas, None, item)
node.update()
node.expand()
root.mainloop()

I couldn't find an easy recipie for using tree widgets in Tkinter. A tree widget is not a built-in widget of Tkinter. And though I found some handful of modules, I found idlelib.TreeWidget to be a nice choice among them. It is sorta built-in, isn't it?

Currently `idlelib' lacks documentations, and is not really used much outside IDLE. I hope this to be fixed soon.