# XXX TO DO:# - popup menu# - support partial or total redisplay# - key bindings (instead of quick-n-dirty bindings on Canvas):# - up/down arrow keys to move focus around# - ditto for page up/down, home/end# - left/right arrows to expand/collapse & move out/in# - more doc strings# - add icons for "file", "module", "class", "method"; better "python" icon# - callback for selection???# - multiple-item selection# - tooltips# - redo geometry without magic numbers# - keep track of object ids to allow more careful cleaning# - optimize tree redraw after expand of subnodeimport osfrom tkinter import *from tkinter.ttk import Frame, Scrollbarfrom idlelib.config import idleConffrom idlelib import zoomheightICONDIR = "Icons"# Look for Icons subdirectory in the same directory as this moduletry:_icondir = os.path.join(os.path.dirname(__file__), ICONDIR)except NameError:_icondir = ICONDIRif os.path.isdir(_icondir):ICONDIR = _icondirelif not os.path.isdir(ICONDIR):raise RuntimeError("can't find icon directory (%r)" % (ICONDIR,))def listicons(icondir=ICONDIR):"""Utility to display the available icons."""root = Tk()import globlist = glob.glob(os.path.join(icondir, "*.gif"))list.sort()images = []row = column = 0for file in list:name = os.path.splitext(os.path.basename(file))[0]image = PhotoImage(file=file, master=root)images.append(image)label = Label(root, image=image, bd=1, relief="raised")label.grid(row=row, column=column)label = Label(root, text=name)label.grid(row=row+1, column=column)column = column + 1if column >= 10:row = row+2column = 0root.images = imagesdef wheel_event(event, widget=None):"""Handle scrollwheel event.For wheel up, event.delta = 120*n on Windows, -1*n on darwin,where n can be > 1 if one scrolls fast. Flicking the wheelgenerates up to maybe 20 events with n up to 10 or more 1.Macs use wheel down (delta = 1*n) to scroll up, so positivedelta means to scroll up on both systems.X-11 sends Control-Button-4,5 events instead.The widget parameter is needed so browser label bindings can passthe underlying canvas.This function depends on widget.yview to not be overridden bya subclass."""up = {EventType.MouseWheel: event.delta > 0,EventType.ButtonPress: event.num == 4}lines = -5 if up[event.type] else 5widget = event.widget if widget is None else widgetwidget.yview(SCROLL, lines, 'units')return 'break'class TreeNode:def __init__(self, canvas, parent, item):self.canvas = canvasself.parent = parentself.item = itemself.state = 'collapsed'self.selected = Falseself.children = []self.x = self.y = Noneself.iconimages = {} # cache of PhotoImage instances for iconsdef destroy(self):for c in self.children[:]:self.children.remove(c)c.destroy()self.parent = Nonedef geticonimage(self, name):try:return self.iconimages[name]except KeyError:passfile, ext = os.path.splitext(name)ext = ext or ".gif"fullname = os.path.join(ICONDIR, file + ext)image = PhotoImage(master=self.canvas, file=fullname)self.iconimages[name] = imagereturn imagedef select(self, event=None):if self.selected:returnself.deselectall()self.selected = Trueself.canvas.delete(self.image_id)self.drawicon()self.drawtext()def deselect(self, event=None):if not self.selected:returnself.selected = Falseself.canvas.delete(self.image_id)self.drawicon()self.drawtext()def deselectall(self):if self.parent:self.parent.deselectall()else:self.deselecttree()def deselecttree(self):if self.selected:self.deselect()for child in self.children:child.deselecttree()def flip(self, event=None):if self.state == 'expanded':self.collapse()else:self.expand()self.item.OnDoubleClick()return "break"def expand(self, event=None):if not self.item._IsExpandable():returnif self.state != 'expanded':self.state = 'expanded'self.update()self.view()def collapse(self, event=None):if self.state != 'collapsed':self.state = 'collapsed'self.update()def view(self):top = self.y - 2bottom = self.lastvisiblechild().y + 17height = bottom - topvisible_top = self.canvas.canvasy(0)visible_height = self.canvas.winfo_height()visible_bottom = self.canvas.canvasy(visible_height)if visible_top <= top and bottom <= visible_bottom:returnx0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion'])if top >= visible_top and height <= visible_height:fraction = top + height - visible_heightelse:fraction = topfraction = float(fraction) / y1self.canvas.yview_moveto(fraction)def lastvisiblechild(self):if self.children and self.state == 'expanded':return self.children[-1].lastvisiblechild()else:return selfdef update(self):if self.parent:self.parent.update()else:oldcursor = self.canvas['cursor']self.canvas['cursor'] = "watch"self.canvas.update()self.canvas.delete(ALL) # XXX could be more subtleself.draw(7, 2)x0, y0, x1, y1 = self.canvas.bbox(ALL)self.canvas.configure(scrollregion=(0, 0, x1, y1))self.canvas['cursor'] = oldcursordef draw(self, x, y):# XXX This hard-codes too many geometry constants!dy = 20self.x, self.y = x, yself.drawicon()self.drawtext()if self.state != 'expanded':return y + dy# draw childrenif not self.children:sublist = self.item._GetSubList()if not sublist:# _IsExpandable() was mistaken; that's allowedreturn y+17for item in sublist:child = self.__class__(self.canvas, self, item)self.children.append(child)cx = x+20cy = y + dycylast = 0for child in self.children:cylast = cyself.canvas.create_line(x+9, cy+7, cx, cy+7, fill="gray50")cy = child.draw(cx, cy)if child.item._IsExpandable():if child.state == 'expanded':iconname = "minusnode"callback = child.collapseelse:iconname = "plusnode"callback = child.expandimage = self.geticonimage(iconname)id = self.canvas.create_image(x+9, cylast+7, image=image)# XXX This leaks bindings until canvas is deleted:self.canvas.tag_bind(id, "<1>", callback)self.canvas.tag_bind(id, "<Double-1>", lambda x: None)id = self.canvas.create_line(x+9, y+10, x+9, cylast+7,##stipple="gray50", # XXX Seems broken in Tk 8.0.xfill="gray50")self.canvas.tag_lower(id) # XXX .lower(id) before Python 1.5.2return cydef drawicon(self):if self.selected:imagename = (self.item.GetSelectedIconName() orself.item.GetIconName() or"openfolder")else:imagename = self.item.GetIconName() or "folder"image = self.geticonimage(imagename)id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image)self.image_id = idself.canvas.tag_bind(id, "<1>", self.select)self.canvas.tag_bind(id, "<Double-1>", self.flip)def drawtext(self):textx = self.x+20-1texty = self.y-4labeltext = self.item.GetLabelText()if labeltext:id = self.canvas.create_text(textx, texty, anchor="nw",text=labeltext)self.canvas.tag_bind(id, "<1>", self.select)self.canvas.tag_bind(id, "<Double-1>", self.flip)x0, y0, x1, y1 = self.canvas.bbox(id)textx = max(x1, 200) + 10text = self.item.GetText() or "<no text>"try:self.entryexcept AttributeError:passelse:self.edit_finish()try:self.labelexcept AttributeError:# padding carefully selected (on Windows) to match Entry widget:self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2)theme = idleConf.CurrentTheme()if self.selected:self.label.configure(idleConf.GetHighlight(theme, 'hilite'))else:self.label.configure(idleConf.GetHighlight(theme, 'normal'))id = self.canvas.create_window(textx, texty,anchor="nw", window=self.label)self.label.bind("<1>", self.select_or_edit)self.label.bind("<Double-1>", self.flip)self.label.bind("<MouseWheel>", lambda e: wheel_event(e, self.canvas))self.label.bind("<Button-4>", lambda e: wheel_event(e, self.canvas))self.label.bind("<Button-5>", lambda e: wheel_event(e, self.canvas))self.text_id = iddef select_or_edit(self, event=None):if self.selected and self.item.IsEditable():self.edit(event)else:self.select(event)def edit(self, event=None):self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0)self.entry.insert(0, self.label['text'])self.entry.selection_range(0, END)self.entry.pack(ipadx=5)self.entry.focus_set()self.entry.bind("<Return>", self.edit_finish)self.entry.bind("<Escape>", self.edit_cancel)def edit_finish(self, event=None):try:entry = self.entrydel self.entryexcept AttributeError:returntext = entry.get()entry.destroy()if text and text != self.item.GetText():self.item.SetText(text)text = self.item.GetText()self.label['text'] = textself.drawtext()self.canvas.focus_set()def edit_cancel(self, event=None):try:entry = self.entrydel self.entryexcept AttributeError:returnentry.destroy()self.drawtext()self.canvas.focus_set()class TreeItem:"""Abstract class representing tree items.Methods should typically be overridden, otherwise a default actionis used."""def __init__(self):"""Constructor. Do whatever you need to do."""def GetText(self):"""Return text string to display."""def GetLabelText(self):"""Return label text string to display in front of text (if any)."""expandable = Nonedef _IsExpandable(self):"""Do not override! Called by TreeNode."""if self.expandable is None:self.expandable = self.IsExpandable()return self.expandabledef IsExpandable(self):"""Return whether there are subitems."""return 1def _GetSubList(self):"""Do not override! Called by TreeNode."""if not self.IsExpandable():return []sublist = self.GetSubList()if not sublist:self.expandable = 0return sublistdef IsEditable(self):"""Return whether the item's text may be edited."""def SetText(self, text):"""Change the item's text (if it is editable)."""def GetIconName(self):"""Return name of icon to be displayed normally."""def GetSelectedIconName(self):"""Return name of icon to be displayed when selected."""def GetSubList(self):"""Return list of items forming sublist."""def OnDoubleClick(self):"""Called on a double-click on the item."""# Example applicationclass FileTreeItem(TreeItem):"""Example TreeItem subclass -- browse the file system."""def __init__(self, path):self.path = pathdef GetText(self):return os.path.basename(self.path) or self.pathdef IsEditable(self):return os.path.basename(self.path) != ""def SetText(self, text):newpath = os.path.dirname(self.path)newpath = os.path.join(newpath, text)if os.path.dirname(newpath) != os.path.dirname(self.path):returntry:os.rename(self.path, newpath)self.path = newpathexcept OSError:passdef GetIconName(self):if not self.IsExpandable():return "python" # XXX wish there was a "file" icondef IsExpandable(self):return os.path.isdir(self.path)def GetSubList(self):try:names = os.listdir(self.path)except OSError:return []names.sort(key = os.path.normcase)sublist = []for name in names:item = FileTreeItem(os.path.join(self.path, name))sublist.append(item)return sublist# A canvas widget with scroll bars and some useful bindingsclass ScrolledCanvas:def __init__(self, master, **opts):if 'yscrollincrement' not in opts:opts['yscrollincrement'] = 17self.master = masterself.frame = Frame(master)self.frame.rowconfigure(0, weight=1)self.frame.columnconfigure(0, weight=1)self.canvas = Canvas(self.frame, **opts)self.canvas.grid(row=0, column=0, sticky="nsew")self.vbar = Scrollbar(self.frame, name="vbar")self.vbar.grid(row=0, column=1, sticky="nse")self.hbar = Scrollbar(self.frame, name="hbar", orient="horizontal")self.hbar.grid(row=1, column=0, sticky="ews")self.canvas['yscrollcommand'] = self.vbar.setself.vbar['command'] = self.canvas.yviewself.canvas['xscrollcommand'] = self.hbar.setself.hbar['command'] = self.canvas.xviewself.canvas.bind("<Key-Prior>", self.page_up)self.canvas.bind("<Key-Next>", self.page_down)self.canvas.bind("<Key-Up>", self.unit_up)self.canvas.bind("<Key-Down>", self.unit_down)self.canvas.bind("<MouseWheel>", wheel_event)self.canvas.bind("<Button-4>", wheel_event)self.canvas.bind("<Button-5>", wheel_event)#if isinstance(master, Toplevel) or isinstance(master, Tk):self.canvas.bind("<Alt-Key-2>", self.zoom_height)self.canvas.focus_set()def page_up(self, event):self.canvas.yview_scroll(-1, "page")return "break"def page_down(self, event):self.canvas.yview_scroll(1, "page")return "break"def unit_up(self, event):self.canvas.yview_scroll(-1, "unit")return "break"def unit_down(self, event):self.canvas.yview_scroll(1, "unit")return "break"def zoom_height(self, event):zoomheight.zoom_height(self.master)return "break"def _tree_widget(parent): # htest #top = Toplevel(parent)x, y = map(int, parent.geometry().split('+')[1:])top.geometry("+%d+%d" % (x+50, y+175))sc = ScrolledCanvas(top, bg="white", highlightthickness=0, takefocus=1)sc.frame.pack(expand=1, fill="both", side=LEFT)item = FileTreeItem(ICONDIR)node = TreeNode(sc.canvas, None, item)node.expand()if __name__ == '__main__':from unittest import mainmain('idlelib.idle_test.test_tree', verbosity=2, exit=False)from idlelib.idle_test.htest import runrun(_tree_widget)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。