Python自習-class19(up)-ファイルトラバーサルを再帰的に実装する

import os
import tkinter
import tkinter.ttk
class TreeWindows:
    def __init__(self):
        self.win=tkinter.Tk()
        self.tree=tkinter.ttk.Treeview(self.win)  #树状
        self.ysb=tkinter.ttk.Scrollbar(self.win,orient="vertical",command=self.tree.yview()) #y滚动条
        self.xsb=tkinter.ttk.Scrollbar(self.win,orient="horizontal",command=self.tree.xview())
        self.tree.configure(yscroll=self.ysb.set,xscroll=self.xsb.set)#关联
        self.tree.grid(row=0,column=0)
        self.tree.heading("#0",text="Path",anchor="w")  #初始化头部
        self.tree.bind("<<TreeviewSelect>>",self.gosel)  #选中绑定
        filepath=r"D:\Python代码\class19"      #路径
        root=self.tree.insert("","end",text=filepath,open="True")   #插入一个节点
        self.laodtree(root,filepath)  #递归

        self.e=tkinter.StringVar()
        self.entry= tkinter.Entry(self.win,textvariable=self.e)
        self.entry.grid(row=0,column=2)


        self.ysb.grid(row=0,column=1,sticky="ns")
        self.xsb.grid(row=1,column=0,sticky="ew")
        self.win.grid()  #表格展示

    def laodtree(self,parent,rootpath):
        for path in os.listdir(rootpath):  #遍历当前目录
            abspath=os.path.join(rootpath,path)  #路径连接
            oid = self.tree.insert(parent,'end',text=path,open=False)#插入树枝
            if os.path.isdir(abspath):
                print("文件夹",abspath)
                self.laodtree(oid,abspath)   #递归调用

    def gosel(self,event):
        self.select=event.widget.selection()   #选择
        for idx in self.select:
            self.e.set(self.tree.item(idx)["text"])
    def show(self):
        self.win.mainloop()

mytree = TreeWindows()
mytree.show()

実行結果:
ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/weixin_46837674/article/details/113481103