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
26 # Look for Icons subdirectory in the same directory as this module
28 _icondir
= os
.path
.join(os
.path
.dirname(__file__
), ICONDIR
)
31 if os
.path
.isdir(_icondir
):
33 elif not os
.path
.isdir(ICONDIR
):
34 raise RuntimeError, "can't find icon directory (%s)" % `ICONDIR`
36 def listicons(icondir
=ICONDIR
):
37 """Utility to display the available icons."""
40 list = glob
.glob(os
.path
.join(icondir
, "*.gif"))
45 name
= os
.path
.splitext(os
.path
.basename(file))[0]
46 image
= PhotoImage(file=file, master
=root
)
48 label
= Label(root
, image
=image
, bd
=1, relief
="raised")
49 label
.grid(row
=row
, column
=column
)
50 label
= Label(root
, text
=name
)
51 label
.grid(row
=row
+1, column
=column
)
61 def __init__(self
, canvas
, parent
, item
):
65 self
.state
= 'collapsed'
68 self
.x
= self
.y
= None
69 self
.iconimages
= {} # cache of PhotoImage instances for icons
72 for c
in self
.children
[:]:
73 self
.children
.remove(c
)
77 def geticonimage(self
, name
):
79 return self
.iconimages
[name
]
82 file, ext
= os
.path
.splitext(name
)
84 fullname
= os
.path
.join(ICONDIR
, file + ext
)
85 image
= PhotoImage(master
=self
.canvas
, file=fullname
)
86 self
.iconimages
[name
] = image
89 def select(self
, event
=None):
94 self
.canvas
.delete(self
.image_id
)
98 def deselect(self
, event
=None):
102 self
.canvas
.delete(self
.image_id
)
106 def deselectall(self
):
108 self
.parent
.deselectall()
112 def deselecttree(self
):
115 for child
in self
.children
:
118 def flip(self
, event
=None):
119 if self
.state
== 'expanded':
123 self
.item
.OnDoubleClick()
126 def expand(self
, event
=None):
127 if not self
.item
._IsExpandable
():
129 if self
.state
!= 'expanded':
130 self
.state
= 'expanded'
134 def collapse(self
, event
=None):
135 if self
.state
!= 'collapsed':
136 self
.state
= 'collapsed'
141 bottom
= self
.lastvisiblechild().y
+ 17
142 height
= bottom
- top
143 visible_top
= self
.canvas
.canvasy(0)
144 visible_height
= self
.canvas
.winfo_height()
145 visible_bottom
= self
.canvas
.canvasy(visible_height
)
146 if visible_top
<= top
and bottom
<= visible_bottom
:
148 x0
, y0
, x1
, y1
= self
.canvas
._getints
(self
.canvas
['scrollregion'])
149 if top
>= visible_top
and height
<= visible_height
:
150 fraction
= top
+ height
- visible_height
153 fraction
= float(fraction
) / y1
154 self
.canvas
.yview_moveto(fraction
)
156 def lastvisiblechild(self
):
157 if self
.children
and self
.state
== 'expanded':
158 return self
.children
[-1].lastvisiblechild()
166 oldcursor
= self
.canvas
['cursor']
167 self
.canvas
['cursor'] = "watch"
169 self
.canvas
.delete(ALL
) # XXX could be more subtle
171 x0
, y0
, x1
, y1
= self
.canvas
.bbox(ALL
)
172 self
.canvas
.configure(scrollregion
=(0, 0, x1
, y1
))
173 self
.canvas
['cursor'] = oldcursor
175 def draw(self
, x
, y
):
176 # XXX This hard-codes too many geometry constants!
177 self
.x
, self
.y
= x
, y
180 if self
.state
!= 'expanded':
183 if not self
.children
:
184 sublist
= self
.item
._GetSubList
()
186 # _IsExpandable() was mistaken; that's allowed
189 child
= self
.__class
__(self
.canvas
, self
, item
)
190 self
.children
.append(child
)
194 for child
in self
.children
:
196 self
.canvas
.create_line(x
+9, cy
+7, cx
, cy
+7, fill
="gray50")
197 cy
= child
.draw(cx
, cy
)
198 if child
.item
._IsExpandable
():
199 if child
.state
== 'expanded':
200 iconname
= "minusnode"
201 callback
= child
.collapse
203 iconname
= "plusnode"
204 callback
= child
.expand
205 image
= self
.geticonimage(iconname
)
206 id = self
.canvas
.create_image(x
+9, cylast
+7, image
=image
)
207 # XXX This leaks bindings until canvas is deleted:
208 self
.canvas
.tag_bind(id, "<1>", callback
)
209 self
.canvas
.tag_bind(id, "<Double-1>", lambda x
: None)
210 id = self
.canvas
.create_line(x
+9, y
+10, x
+9, cylast
+7,
211 ##stipple="gray50", # XXX Seems broken in Tk 8.0.x
213 self
.canvas
.tag_lower(id) # XXX .lower(id) before Python 1.5.2
218 imagename
= (self
.item
.GetSelectedIconName() or
219 self
.item
.GetIconName() or
222 imagename
= self
.item
.GetIconName() or "folder"
223 image
= self
.geticonimage(imagename
)
224 id = self
.canvas
.create_image(self
.x
, self
.y
, anchor
="nw", image
=image
)
226 self
.canvas
.tag_bind(id, "<1>", self
.select
)
227 self
.canvas
.tag_bind(id, "<Double-1>", self
.flip
)
232 labeltext
= self
.item
.GetLabelText()
234 id = self
.canvas
.create_text(textx
, texty
, anchor
="nw",
236 self
.canvas
.tag_bind(id, "<1>", self
.select
)
237 self
.canvas
.tag_bind(id, "<Double-1>", self
.flip
)
238 x0
, y0
, x1
, y1
= self
.canvas
.bbox(id)
239 textx
= max(x1
, 200) + 10
240 text
= self
.item
.GetText() or "<no text>"
243 except AttributeError:
249 except AttributeError:
250 # padding carefully selected (on Windows) to match Entry widget:
251 self
.label
= Label(self
.canvas
, text
=text
, bd
=0, padx
=2, pady
=2)
253 self
.label
.configure(fg
="white", bg
="darkblue")
255 self
.label
.configure(fg
="black", bg
="white")
256 id = self
.canvas
.create_window(textx
, texty
,
257 anchor
="nw", window
=self
.label
)
258 self
.label
.bind("<1>", self
.select_or_edit
)
259 self
.label
.bind("<Double-1>", self
.flip
)
262 def select_or_edit(self
, event
=None):
263 if self
.selected
and self
.item
.IsEditable():
268 def edit(self
, event
=None):
269 self
.entry
= Entry(self
.label
, bd
=0, highlightthickness
=1, width
=0)
270 self
.entry
.insert(0, self
.label
['text'])
271 self
.entry
.selection_range(0, END
)
272 self
.entry
.pack(ipadx
=5)
273 self
.entry
.focus_set()
274 self
.entry
.bind("<Return>", self
.edit_finish
)
275 self
.entry
.bind("<Escape>", self
.edit_cancel
)
277 def edit_finish(self
, event
=None):
281 except AttributeError:
285 if text
and text
!= self
.item
.GetText():
286 self
.item
.SetText(text
)
287 text
= self
.item
.GetText()
288 self
.label
['text'] = text
290 self
.canvas
.focus_set()
292 def edit_cancel(self
, event
=None):
296 except AttributeError:
300 self
.canvas
.focus_set()
305 """Abstract class representing tree items.
307 Methods should typically be overridden, otherwise a default action
313 """Constructor. Do whatever you need to do."""
316 """Return text string to display."""
318 def GetLabelText(self
):
319 """Return label text string to display in front of text (if any)."""
323 def _IsExpandable(self
):
324 """Do not override! Called by TreeNode."""
325 if self
.expandable
is None:
326 self
.expandable
= self
.IsExpandable()
327 return self
.expandable
329 def IsExpandable(self
):
330 """Return whether there are subitems."""
333 def _GetSubList(self
):
334 """Do not override! Called by TreeNode."""
335 if not self
.IsExpandable():
337 sublist
= self
.GetSubList()
342 def IsEditable(self
):
343 """Return whether the item's text may be edited."""
345 def SetText(self
, text
):
346 """Change the item's text (if it is editable)."""
348 def GetIconName(self
):
349 """Return name of icon to be displayed normally."""
351 def GetSelectedIconName(self
):
352 """Return name of icon to be displayed when selected."""
354 def GetSubList(self
):
355 """Return list of items forming sublist."""
357 def OnDoubleClick(self
):
358 """Called on a double-click on the item."""
361 # Example application
363 class FileTreeItem(TreeItem
):
365 """Example TreeItem subclass -- browse the file system."""
367 def __init__(self
, path
):
371 return os
.path
.basename(self
.path
) or self
.path
373 def IsEditable(self
):
374 return os
.path
.basename(self
.path
) != ""
376 def SetText(self
, text
):
377 newpath
= os
.path
.dirname(self
.path
)
378 newpath
= os
.path
.join(newpath
, text
)
379 if os
.path
.dirname(newpath
) != os
.path
.dirname(self
.path
):
382 os
.rename(self
.path
, newpath
)
387 def GetIconName(self
):
388 if not self
.IsExpandable():
389 return "python" # XXX wish there was a "file" icon
391 def IsExpandable(self
):
392 return os
.path
.isdir(self
.path
)
394 def GetSubList(self
):
396 names
= os
.listdir(self
.path
)
399 names
.sort(lambda a
, b
: cmp(os
.path
.normcase(a
), os
.path
.normcase(b
)))
402 item
= FileTreeItem(os
.path
.join(self
.path
, name
))
407 # A canvas widget with scroll bars and some useful bindings
409 class ScrolledCanvas
:
410 def __init__(self
, master
, **opts
):
411 if not opts
.has_key('yscrollincrement'):
412 opts
['yscrollincrement'] = 17
414 self
.frame
= Frame(master
)
415 self
.frame
.rowconfigure(0, weight
=1)
416 self
.frame
.columnconfigure(0, weight
=1)
417 self
.canvas
= apply(Canvas
, (self
.frame
,), opts
)
418 self
.canvas
.grid(row
=0, column
=0, sticky
="nsew")
419 self
.vbar
= Scrollbar(self
.frame
, name
="vbar")
420 self
.vbar
.grid(row
=0, column
=1, sticky
="nse")
421 self
.hbar
= Scrollbar(self
.frame
, name
="hbar", orient
="horizontal")
422 self
.hbar
.grid(row
=1, column
=0, sticky
="ews")
423 self
.canvas
['yscrollcommand'] = self
.vbar
.set
424 self
.vbar
['command'] = self
.canvas
.yview
425 self
.canvas
['xscrollcommand'] = self
.hbar
.set
426 self
.hbar
['command'] = self
.canvas
.xview
427 self
.canvas
.bind("<Key-Prior>", self
.page_up
)
428 self
.canvas
.bind("<Key-Next>", self
.page_down
)
429 self
.canvas
.bind("<Key-Up>", self
.unit_up
)
430 self
.canvas
.bind("<Key-Down>", self
.unit_down
)
431 if isinstance(master
, Toplevel
) or isinstance(master
, Tk
):
432 self
.canvas
.bind("<Alt-F2>", self
.zoom_height
)
433 self
.canvas
.focus_set()
434 def page_up(self
, event
):
435 self
.canvas
.yview_scroll(-1, "page")
437 def page_down(self
, event
):
438 self
.canvas
.yview_scroll(1, "page")
440 def unit_up(self
, event
):
441 self
.canvas
.yview_scroll(-1, "unit")
443 def unit_down(self
, event
):
444 self
.canvas
.yview_scroll(1, "unit")
446 def zoom_height(self
, event
):
447 ZoomHeight
.zoom_height(self
.master
)
455 root
= Toplevel(PyShell
.root
)
456 root
.configure(bd
=0, bg
="yellow")
458 sc
= ScrolledCanvas(root
, bg
="white", highlightthickness
=0, takefocus
=1)
459 sc
.frame
.pack(expand
=1, fill
="both")
460 item
= FileTreeItem("C:/windows/desktop")
461 node
= TreeNode(sc
.canvas
, None, item
)
465 # test w/o scrolling canvas
468 canvas
= Canvas(root
, bg
="white", highlightthickness
=0)
469 canvas
.pack(expand
=1, fill
="both")
470 item
= FileTreeItem(os
.curdir
)
471 node
= TreeNode(canvas
, None, item
)
475 if __name__
== '__main__':