3 # - support partial or total redisplay
4 # - key bindings (instead of quick-n-dirty bindings on Canvas):
5 # - up/down arrow keys to move focus around
6 # - ditto for page up/down, home/end
7 # - left/right arrows to expand/collapse & move out/in
9 # - add icons for "file", "module", "class", "method"; better "python" icon
10 # - callback for selection???
11 # - multiple-item selection
13 # - redo geometry without magic numbers
14 # - keep track of object ids to allow more careful cleaning
15 # - optimize tree redraw after expand of subnode
27 # Look for Icons subdirectory in the same directory as this module
29 _icondir
= os
.path
.join(os
.path
.dirname(__file__
), ICONDIR
)
32 if os
.path
.isdir(_icondir
):
34 elif not os
.path
.isdir(ICONDIR
):
35 raise RuntimeError, "can't find icon directory (%s)" % `ICONDIR`
37 def listicons(icondir
=ICONDIR
):
38 """Utility to display the available icons."""
41 list = glob
.glob(os
.path
.join(icondir
, "*.gif"))
46 name
= os
.path
.splitext(os
.path
.basename(file))[0]
47 image
= PhotoImage(file=file, master
=root
)
49 label
= Label(root
, image
=image
, bd
=1, relief
="raised")
50 label
.grid(row
=row
, column
=column
)
51 label
= Label(root
, text
=name
)
52 label
.grid(row
=row
+1, column
=column
)
62 def __init__(self
, canvas
, parent
, item
):
66 self
.state
= 'collapsed'
69 self
.x
= self
.y
= None
70 self
.iconimages
= {} # cache of PhotoImage instances for icons
73 for c
in self
.children
[:]:
74 self
.children
.remove(c
)
78 def geticonimage(self
, name
):
80 return self
.iconimages
[name
]
83 file, ext
= os
.path
.splitext(name
)
85 fullname
= os
.path
.join(ICONDIR
, file + ext
)
86 image
= PhotoImage(master
=self
.canvas
, file=fullname
)
87 self
.iconimages
[name
] = image
90 def select(self
, event
=None):
95 self
.canvas
.delete(self
.image_id
)
99 def deselect(self
, event
=None):
100 if not self
.selected
:
103 self
.canvas
.delete(self
.image_id
)
107 def deselectall(self
):
109 self
.parent
.deselectall()
113 def deselecttree(self
):
116 for child
in self
.children
:
119 def flip(self
, event
=None):
120 if self
.state
== 'expanded':
124 self
.item
.OnDoubleClick()
127 def expand(self
, event
=None):
128 if not self
.item
._IsExpandable
():
130 if self
.state
!= 'expanded':
131 self
.state
= 'expanded'
135 def collapse(self
, event
=None):
136 if self
.state
!= 'collapsed':
137 self
.state
= 'collapsed'
142 bottom
= self
.lastvisiblechild().y
+ 17
143 height
= bottom
- top
144 visible_top
= self
.canvas
.canvasy(0)
145 visible_height
= self
.canvas
.winfo_height()
146 visible_bottom
= self
.canvas
.canvasy(visible_height
)
147 if visible_top
<= top
and bottom
<= visible_bottom
:
149 x0
, y0
, x1
, y1
= self
.canvas
._getints
(self
.canvas
['scrollregion'])
150 if top
>= visible_top
and height
<= visible_height
:
151 fraction
= top
+ height
- visible_height
154 fraction
= float(fraction
) / y1
155 self
.canvas
.yview_moveto(fraction
)
157 def lastvisiblechild(self
):
158 if self
.children
and self
.state
== 'expanded':
159 return self
.children
[-1].lastvisiblechild()
167 oldcursor
= self
.canvas
['cursor']
168 self
.canvas
['cursor'] = "watch"
170 self
.canvas
.delete(ALL
) # XXX could be more subtle
172 x0
, y0
, x1
, y1
= self
.canvas
.bbox(ALL
)
173 self
.canvas
.configure(scrollregion
=(0, 0, x1
, y1
))
174 self
.canvas
['cursor'] = oldcursor
176 def draw(self
, x
, y
):
177 # XXX This hard-codes too many geometry constants!
178 self
.x
, self
.y
= x
, y
181 if self
.state
!= 'expanded':
184 if not self
.children
:
185 sublist
= self
.item
._GetSubList
()
187 # _IsExpandable() was mistaken; that's allowed
190 child
= TreeNode(self
.canvas
, self
, item
)
191 self
.children
.append(child
)
195 for child
in self
.children
:
197 self
.canvas
.create_line(x
+9, cy
+7, cx
, cy
+7, fill
="gray50")
198 cy
= child
.draw(cx
, cy
)
199 if child
.item
._IsExpandable
():
200 if child
.state
== 'expanded':
201 iconname
= "minusnode"
202 callback
= child
.collapse
204 iconname
= "plusnode"
205 callback
= child
.expand
206 image
= self
.geticonimage(iconname
)
207 id = self
.canvas
.create_image(x
+9, cylast
+7, image
=image
)
208 # XXX This leaks bindings until canvas is deleted:
209 self
.canvas
.tag_bind(id, "<1>", callback
)
210 self
.canvas
.tag_bind(id, "<Double-1>", lambda x
: None)
211 id = self
.canvas
.create_line(x
+9, y
+10, x
+9, cylast
+7,
212 ##stipple="gray50", # XXX Seems broken in Tk 8.0.x
214 self
.canvas
.tag_lower(id) # XXX .lower(id) before Python 1.5.2
219 imagename
= (self
.item
.GetSelectedIconName() or
220 self
.item
.GetIconName() or
223 imagename
= self
.item
.GetIconName() or "folder"
224 image
= self
.geticonimage(imagename
)
225 id = self
.canvas
.create_image(self
.x
, self
.y
, anchor
="nw", image
=image
)
227 self
.canvas
.tag_bind(id, "<1>", self
.select
)
228 self
.canvas
.tag_bind(id, "<Double-1>", self
.flip
)
233 labeltext
= self
.item
.GetLabelText()
235 id = self
.canvas
.create_text(textx
, texty
, anchor
="nw",
237 self
.canvas
.tag_bind(id, "<1>", self
.select
)
238 self
.canvas
.tag_bind(id, "<Double-1>", self
.flip
)
239 x0
, y0
, x1
, y1
= self
.canvas
.bbox(id)
240 textx
= max(x1
, 200) + 10
241 text
= self
.item
.GetText() or "<no text>"
244 except AttributeError:
250 except AttributeError:
251 # padding carefully selected (on Windows) to match Entry widget:
252 self
.label
= Label(self
.canvas
, text
=text
, bd
=0, padx
=2, pady
=2)
254 self
.label
.configure(fg
="white", bg
="darkblue")
256 self
.label
.configure(fg
="black", bg
="white")
257 id = self
.canvas
.create_window(textx
, texty
,
258 anchor
="nw", window
=self
.label
)
259 self
.label
.bind("<1>", self
.select_or_edit
)
260 self
.label
.bind("<Double-1>", self
.flip
)
263 def select_or_edit(self
, event
=None):
264 if self
.selected
and self
.item
.IsEditable():
269 def edit(self
, event
=None):
270 self
.entry
= Entry(self
.label
, bd
=0, highlightthickness
=1, width
=0)
271 self
.entry
.insert(0, self
.label
['text'])
272 self
.entry
.selection_range(0, END
)
273 self
.entry
.pack(ipadx
=5)
274 self
.entry
.focus_set()
275 self
.entry
.bind("<Return>", self
.edit_finish
)
276 self
.entry
.bind("<Escape>", self
.edit_cancel
)
278 def edit_finish(self
, event
=None):
282 except AttributeError:
286 if text
and text
!= self
.item
.GetText():
287 self
.item
.SetText(text
)
288 text
= self
.item
.GetText()
289 self
.label
['text'] = text
291 self
.canvas
.focus_set()
293 def edit_cancel(self
, event
=None):
295 self
.canvas
.focus_set()
300 """Abstract class representing tree items.
302 Methods should typically be overridden, otherwise a default action
308 """Constructor. Do whatever you need to do."""
311 """Return text string to display."""
313 def GetLabelText(self
):
314 """Return label text string to display in front of text (if any)."""
318 def _IsExpandable(self
):
319 """Do not override! Called by TreeNode."""
320 if self
.expandable
is None:
321 self
.expandable
= self
.IsExpandable()
322 return self
.expandable
324 def IsExpandable(self
):
325 """Return whether there are subitems."""
328 def _GetSubList(self
):
329 """Do not override! Called by TreeNode."""
330 if not self
.IsExpandable():
332 sublist
= self
.GetSubList()
337 def IsEditable(self
):
338 """Return whether the item's text may be edited."""
340 def SetText(self
, text
):
341 """Change the item's text (if it is editable)."""
343 def GetIconName(self
):
344 """Return name of icon to be displayed normally."""
346 def GetSelectedIconName(self
):
347 """Return name of icon to be displayed when selected."""
349 def GetSubList(self
):
350 """Return list of items forming sublist."""
352 def OnDoubleClick(self
):
353 """Called on a double-click on the item."""
356 # Example application
358 class FileTreeItem(TreeItem
):
360 """Example TreeItem subclass -- browse the file system."""
362 def __init__(self
, path
):
366 return os
.path
.basename(self
.path
) or self
.path
368 def IsEditable(self
):
369 return os
.path
.basename(self
.path
) != ""
371 def SetText(self
, text
):
372 newpath
= os
.path
.dirname(self
.path
)
373 newpath
= os
.path
.join(newpath
, text
)
374 if os
.path
.dirname(newpath
) != os
.path
.dirname(self
.path
):
377 os
.rename(self
.path
, newpath
)
382 def GetIconName(self
):
383 if not self
.IsExpandable():
384 return "python" # XXX wish there was a "file" icon
386 def IsExpandable(self
):
387 return os
.path
.isdir(self
.path
)
389 def GetSubList(self
):
391 names
= os
.listdir(self
.path
)
394 names
.sort(lambda a
, b
: cmp(os
.path
.normcase(a
), os
.path
.normcase(b
)))
397 item
= FileTreeItem(os
.path
.join(self
.path
, name
))
402 # A canvas widget with scroll bars and some useful bindings
404 class ScrolledCanvas
:
405 def __init__(self
, master
, **opts
):
406 if not opts
.has_key('yscrollincrement'):
407 opts
['yscrollincrement'] = 17
409 self
.frame
= Frame(master
)
410 self
.frame
.rowconfigure(0, weight
=1)
411 self
.frame
.columnconfigure(0, weight
=1)
412 self
.canvas
= apply(Canvas
, (self
.frame
,), opts
)
413 self
.canvas
.grid(row
=0, column
=0, sticky
="nsew")
414 self
.vbar
= Scrollbar(self
.frame
, name
="vbar")
415 self
.vbar
.grid(row
=0, column
=1, sticky
="nse")
416 self
.hbar
= Scrollbar(self
.frame
, name
="hbar", orient
="horizontal")
417 self
.hbar
.grid(row
=1, column
=0, sticky
="ews")
418 self
.canvas
['yscrollcommand'] = self
.vbar
.set
419 self
.vbar
['command'] = self
.canvas
.yview
420 self
.canvas
['xscrollcommand'] = self
.hbar
.set
421 self
.hbar
['command'] = self
.canvas
.xview
422 self
.canvas
.bind("<Key-Prior>", self
.page_up
)
423 self
.canvas
.bind("<Key-Next>", self
.page_down
)
424 self
.canvas
.bind("<Key-Up>", self
.unit_up
)
425 self
.canvas
.bind("<Key-Down>", self
.unit_down
)
426 if isinstance(master
, Toplevel
) or isinstance(master
, Tk
):
427 self
.canvas
.bind("<Alt-F2>", self
.zoom_height
)
428 self
.canvas
.focus_set()
429 def page_up(self
, event
):
430 self
.canvas
.yview_scroll(-1, "page")
432 def page_down(self
, event
):
433 self
.canvas
.yview_scroll(1, "page")
435 def unit_up(self
, event
):
436 self
.canvas
.yview_scroll(-1, "unit")
438 def unit_down(self
, event
):
439 self
.canvas
.yview_scroll(1, "unit")
441 def zoom_height(self
, event
):
442 ZoomHeight
.zoom_height(self
.master
)
450 root
= Toplevel(PyShell
.root
)
451 root
.configure(bd
=0, bg
="yellow")
453 sc
= ScrolledCanvas(root
, bg
="white", highlightthickness
=0, takefocus
=1)
454 sc
.frame
.pack(expand
=1, fill
="both")
455 item
= FileTreeItem("C:/windows/desktop")
456 node
= TreeNode(sc
.canvas
, None, item
)
460 # test w/o scrolling canvas
463 canvas
= Canvas(root
, bg
="white", highlightthickness
=0)
464 canvas
.pack(expand
=1, fill
="both")
465 item
= FileTreeItem(os
.curdir
)
466 node
= TreeNode(canvas
, None, item
)
470 if __name__
== '__main__':