You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Tkinter实现选择多目录并展示对应目录下的全部文件内容

Tkinter 目录选择展示文件列表修改方案

完整可运行代码

from tkinter import *
from tkinter import filedialog
import os

root = Tk()
root.geometry('400x300')
root.grid_rowconfigure(0, weight = 1)
root.grid_columnconfigure(0, weight = 1)

def get_directories():
    selected_dir = filedialog.askdirectory()
    # 处理用户取消选择的情况
    if not selected_dir:
        return
    # 清空文本框原有内容
    text_box.delete(1.0, END)
    # 遍历获取目录下所有内容名称
    for file_name in os.listdir(selected_dir):
        text_box.insert(END, file_name + "\n")

b1 = Button(root, text='select directories...', command = get_directories)
b1.pack(pady=5)

# 新增文本框组件,支持自适应窗口大小
text_box = Text(root, wrap=WORD)
text_box.pack(fill=BOTH, expand=True, padx=5, pady=5)

root.mainloop()

核心修改说明

  • 新增导入os模块,用于读取目录下的文件/文件夹列表
  • 调整窗口尺寸,适配文本框的展示需求
  • 移除冗余的全局dirs列表,直接在触发函数内处理选中的目录
  • 新增Text文本框组件,设置fill=BOTH和expand=True属性实现窗口大小自适应
  • 重写按钮触发函数逻辑:
    • 增加空值判断,避免用户取消选择时报错
    • 每次写入新内容前清空文本框,避免历史内容堆叠
    • 调用os.listdir读取选中目录下的所有内容名称,逐行写入文本框

可选优化:仅展示文件排除子文件夹

如果不需要展示子文件夹名称,只展示纯文件,可将遍历逻辑替换为以下代码:

for file_name in os.listdir(selected_dir):
    full_path = os.path.join(selected_dir, file_name)
    if os.path.isfile(full_path):
        text_box.insert(END, file_name + "\n")

内容的提问来源于stack exchange,提问作者Amel Hadfi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 16:18:03