SherCoder
SherCoder

Reputation: 688

Create tree hierarchy using os.walk and gobject gtk+3

I am trying to create a simple file browser. I am trying to add a tree hierarchy for files. I wrote a sample method that prints the hierarchy correctly, but I am having hard time to model the same concept to create Gtk.TreeStore object. Following is my sample code to list the files:

def list_files(startpath):
    for dirname, subdirs, files in os.walk(startpath):
        level = dirname.replace(startpath, '').count(os.sep)
        indent = ' ' * 4 * (level)
        print('{}{}/'.format(indent, os.path.basename(dirname)))
        subindent = ' ' * 4 * (level + 1)
        for f in files:
            print('{}{}'.format(subindent, f))

And following is the code to create a Gtk.TreeStore:

def add_paned(self):
    paned = Gtk.Paned.new(Gtk.Orientation.HORIZONTAL)

    TEST_DIR = '/home/myuser'
    store = MyTreeStore(str)
    store.generate_tree(TEST_DIR)

    treeview = Gtk.TreeView(store)
    renderer = Gtk.CellRendererText()
    column = Gtk.TreeViewColumn("FileName", renderer, text=0)
    treeview.append_column(column)

    paned.add1(treeview)
    self.add(paned)
    return paned

MyTreeStore class:

from gi.repository import Gtk
import os

class MyTreeStore(Gtk.TreeStore):
def __init__(self, *arg):
    super(MyTreeStore, self).__init__(*arg)

def generate_tree(self, path):
    parent = None;
    for dirname, subdirs, files in sorted(os.walk(path)):
        # level = dirname.replace(path, '').count(os.sep)
        # iter = self.get_iter_from_string('{}'.format(level))
        parent = self.append(parent, [os.path.basename(dirname)])
        print(os.path.basename(dirname))
        for file in sorted(files):
           self.append(parent, [file])

I am just stuck on creating proper iterators when appending file names. Right now the above code just nest all directories since the parent is the last directory appended to the store. Any ideas how I would go about doing this?

Upvotes: 1

Views: 297

Answers (1)

Samet Burgazoğlu
Samet Burgazoğlu

Reputation: 59

It's been 8 years since the question was asked. But for those who look here later, here is the solution:

def generate_tree(self, path):
    store = Gtk.TreeStore(str)
    base_path = os.path.dirname(path)
    directories = {base_path: None}
    for dirname, subdirs, files in os.walk(path):
        parent_directory_row = directories[os.path.dirname(dirname)]
        directories[dirname] = store.append(parent_directory_row, [os.path.basename(dirname)])
        for file in files:
            store.append(directories[dirname], [file])
    return store

Upvotes: 1

Related Questions