[Python-checkins] r62991 - sandbox/trunk/ttk-gsoc/samples/dirbrowser.py

guilherme.polo python-checkins at python.org
Sat May 10 15:16:39 CEST 2008


Author: guilherme.polo
Date: Sat May 10 15:16:38 2008
New Revision: 62991

Log:
Added a demo for showing Treeview a bit.

Added:
   sandbox/trunk/ttk-gsoc/samples/dirbrowser.py

Added: sandbox/trunk/ttk-gsoc/samples/dirbrowser.py
==============================================================================
--- (empty file)
+++ sandbox/trunk/ttk-gsoc/samples/dirbrowser.py	Sat May 10 15:16:38 2008
@@ -0,0 +1,74 @@
+"""A directory browser using Ttk Treeview.
+
+Based on an example found at:
+http://bitwalk.blogspot.com/2008/01/ttktreeview.html
+"""
+
+import os
+import sys
+import Tkinter
+
+if sys.version_info[0] > 2:
+    from tkinter import ttk
+else:
+    import Ttk as ttk
+
+def populate_tree(tree, node):
+    if tree.set(node, "type") != 'directory':
+        return
+
+    path = tree.set(node, "fullpath")
+    tree.delete(tree.get_children(node))
+
+    for p in os.listdir(path):
+        p = os.path.join(path, p)
+        if os.path.isdir(p):
+            type = "directory"
+        elif os.path.isfile(p):
+            type = "file"
+
+        id = tree.insert(node, "end", text=os.path.split(p)[1], 
+            values=[p, type])
+
+        if type == 'directory':
+            tree.insert(id, 0, text="dummy")
+            tree.item(id, text=os.path.split(p)[1])
+        elif type == 'file':
+            size = os.stat(p).st_size
+            tree.set(id, "size", "%d bytes" % size)
+
+def popuplate_roots(tree):
+    dir = os.path.abspath('.')
+    node = tree.insert('', 'end', text=dir, values=[dir, "directory"])
+    populate_tree(tree, node)
+
+def update_tree(event):
+    tree = event.widget
+    populate_tree(tree, tree.focus())
+
+root = Tkinter.Tk()
+
+vsb = ttk.Scrollbar(orient="vertical")
+hsb = ttk.Scrollbar(orient="horizontal")
+
+tree = ttk.Treeview(columns=("fullpath", "type", "size"), 
+    displaycolumns="size", yscroll=vsb.set, xscroll=hsb.set)
+
+vsb['command'] = tree.yview
+hsb['command'] = tree.xview
+
+tree.heading("#0", text="Directory Structure")
+tree.heading("size", text="File Size")
+tree.column("size", stretch=0, width=70)
+
+popuplate_roots(tree)
+tree.bind('<<TreeviewOpen>>', update_tree)
+
+# Arrange the tree and its scrollbars in the toplevel
+tree.grid(column=0, row=0, sticky='nswe')
+vsb.grid(column=1, row=0, sticky='ns')
+hsb.grid(column=0, row=1, sticky='ew')
+root.grid_columnconfigure(0, weight=1)
+root.grid_rowconfigure(0, weight=1)
+
+root.mainloop()


More information about the Python-checkins mailing list