gpt4 book ai didi

python - 使用 tkinter Treeview 小部件显示目录内容

转载 作者:太空狗 更新时间:2023-10-29 19:33:45 31 4
gpt4 key购买 nike

目前我正在开发一个程序,它有自己的项目文件,里面有子文件,我想知道如何使用 treeview 小部件显示项目文件中的所有子文件,Any想法?

提前致谢!

最佳答案

有一个example in the source code of CPython关于如何用目录的内容递归地填充 Treeview,这基本上就是它的工作原理(我删除了事件绑定(bind)并将其包装在一个类中以提高可读性):

import os
import tkinter as tk
import tkinter.ttk as ttk

class App(tk.Frame):
def __init__(self, master, path):
tk.Frame.__init__(self, master)
self.tree = ttk.Treeview(self)
ysb = ttk.Scrollbar(self, orient='vertical', command=self.tree.yview)
xsb = ttk.Scrollbar(self, orient='horizontal', command=self.tree.xview)
self.tree.configure(yscroll=ysb.set, xscroll=xsb.set)
self.tree.heading('#0', text=path, anchor='w')

abspath = os.path.abspath(path)
root_node = self.tree.insert('', 'end', text=abspath, open=True)
self.process_directory(root_node, abspath)

self.tree.grid(row=0, column=0)
ysb.grid(row=0, column=1, sticky='ns')
xsb.grid(row=1, column=0, sticky='ew')
self.grid()

def process_directory(self, parent, path):
for p in os.listdir(path):
abspath = os.path.join(path, p)
isdir = os.path.isdir(abspath)
oid = self.tree.insert(parent, 'end', text=p, open=False)
if isdir:
self.process_directory(oid, abspath)

root = tk.Tk()
path_to_my_project = # ...
app = App(root, path=path_to_my_project)
app.mainloop()

更新:正如@ArtOfWarfare 提到的,可以使用 <<TreeviewOpen>> 延迟填充树。事件。为了模拟关闭的节点,我使用了一个空的子项,它在打开目录时被删除:

import os
import tkinter as tk
import tkinter.ttk as ttk


class App(object):
def __init__(self, master, path):
self.nodes = dict()
frame = tk.Frame(master)
self.tree = ttk.Treeview(frame)
ysb = ttk.Scrollbar(frame, orient='vertical', command=self.tree.yview)
xsb = ttk.Scrollbar(frame, orient='horizontal', command=self.tree.xview)
self.tree.configure(yscroll=ysb.set, xscroll=xsb.set)
self.tree.heading('#0', text='Project tree', anchor='w')

self.tree.grid()
ysb.grid(row=0, column=1, sticky='ns')
xsb.grid(row=1, column=0, sticky='ew')
frame.grid()

abspath = os.path.abspath(path)
self.insert_node('', abspath, abspath)
self.tree.bind('<<TreeviewOpen>>', self.open_node)

def insert_node(self, parent, text, abspath):
node = self.tree.insert(parent, 'end', text=text, open=False)
if os.path.isdir(abspath):
self.nodes[node] = abspath
self.tree.insert(node, 'end')

def open_node(self, event):
node = self.tree.focus()
abspath = self.nodes.pop(node, None)
if abspath:
self.tree.delete(self.tree.get_children(node))
for p in os.listdir(abspath):
self.insert_node(node, p, os.path.join(abspath, p))


if __name__ == '__main__':
root = tk.Tk()
app = App(root, path='.')
root.mainloop()

关于python - 使用 tkinter Treeview 小部件显示目录内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16746387/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com