python目录树生成器

在这里插入图片描述
代码如下:

import os
from colorama import Fore, Style, init
from tkinter import Tk, Label, Entry, Button, Text, Scrollbar, RIGHT, Y, END

# 初始化 colorama
init(autoreset=True)

def print_directory_tree(root_dir, text_widget, indent='', last=True):
    """递归打印目录树并显示在文本框中"""
    if os.path.isfile(root_dir):
        text_widget.insert(END, f'{indent}{"└── " if last else "├── "} {os.path.basename(root_dir)}\n')
    else:
        text_widget.insert(END, f'{indent}{"└── " if last else "├── "} {os.path.basename(root_dir)}\\\n')
        indent += '    ' if last else '│   '
        items = os.listdir(root_dir)
        for i, item in enumerate(items):
            last = i == len(items) - 1
            print_directory_tree(os.path.join(root_dir, item), text_widget, indent, last)

def generate_tree():
    root_dir = entry.get()
    text_widget.delete(1.0, END)
    text_widget.insert(END, f'{root_dir}\n')
    print_directory_tree(root_dir, text_widget)

# 创建主窗口
root = Tk()
root.title("目录树生成器")

# 创建标签、输入框和按钮
label = Label(root, text="输入目录路径:")
label.pack()

entry = Entry(root, width=50)
entry.pack()

button = Button(root, text="生成目录树", command=generate_tree)
button.pack()

# 创建文本框和滚动条
text_widget = Text(root, wrap='none', height=25, width=80)
scrollbar = Scrollbar(root, command=text_widget.yview)
text_widget.configure(yscrollcommand=scrollbar.set)
scrollbar.pack(side=RIGHT, fill=Y)
text_widget.pack(side=RIGHT, fill=Y)

# 运行主循环
root.mainloop()

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值