1

我正在尝试创建一个简单的文件浏览器。我正在尝试为文件添加树层次结构。我编写了一个正确打印层次结构的示例方法,但是我很难为相同的概念建模以创建Gtk.TreeStore对象。以下是我列出文件的示例代码:

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))

以下是创建一个的代码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班级:

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])

在附加文件名时,我只是坚持创建正确的迭代器。现在上面的代码只是嵌套了所有目录,因为父目录是最后一个附加到商店的目录。有什么想法我会怎么做?

4

1 回答 1

1

问这个问题已经8年了。但对于那些稍后看这里的人来说,这里是解决方案:

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
于 2021-12-03T14:58:16.637 回答