python tkinter中文件夹显示树状结构

本文介绍了一个使用Python的Tkinter和ttk库实现的文件夹树状结构显示程序,通过递归遍历文件夹并展示其内容。用户可以浏览ProgramFiles文件夹的子目录结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果如下图:

# 文件夹显示树状结构
import tkinter
from tkinter import ttk
import os
class TreeWindow(tkinter.Frame):
    def __init__(self,master,path):
        frame = tkinter.Frame(master)
        frame.pack()
 
        self.tree = ttk.Treeview(frame)
        self.tree.pack()
        root = self.tree.insert("","end",text=self.getlastPath(path),open=True)
        self.loadTree(root,path)
    def loadTree(self,parent,path):
        for filepath in os.listdir(path):
            #文件的绝对路径
            abs = os.path.join(path,filepath)

            #插入树枝
            treey = self.tree.insert(parent,"end",text=self.getlastPath(filepath))
            #判断是否是目录,是目录再去添加树枝,使用递归
            if os.path.isdir(abs):
                self.loadTree(treey,abs)
    #求文件的最后一个名字
    def getlastPath(self,path):
        pathList = os.path.split(path)
        return pathList[-1]
    
#创建主窗口
win = tkinter.Tk()
win.title("主界面")
win.geometry("300x300")
path = "D:\\Program Files"
treewin = TreeWindow(win,path)
 
win.mainloop()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值