您可以按照以下步骤使用 TreeView 控件显示文件夹下的所有文件列表:
import os
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("File Explorer")
tree = ttk.Treeview(root)
tree.pack()
def populate_treeview(path, parent):
for item in os.listdir(path):
item_path = os.path.join(path, item)
isdir = os.path.isdir(item_path)
item_id = tree.insert(parent, "end", text=item, open=False, tags=("directory" if isdir else "file",))
if isdir:
populate_treeview(item_path, item_id)
tree["columns"] = ("type",)
tree.column("#0", width=300)
tree.column("type", width=100)
tree.heading("#0", text="Name")
tree.heading("type", text="Type")
root_directory = "/path/to/directory" # 替换为您想要显示文件列表的文件夹路径
populate_treeview(root_directory, "")
root.mainloop()
完整示例代码如下:
import os
import tkinter as tk
from tkinter import ttk
def populate_treeview(path, parent):
for item in os.listdir(path):
item_path = os.path.join(path, item)
isdir = os.path.isdir(item_path)
item_id = tree.insert(parent, "end", text=item, open=False, tags=("directory" if isdir else "file",))
if isdir:
populate_treeview(item_path, item_id)
root = tk.Tk()
root.title("File Explorer")
tree = ttk.Treeview(root)
tree.pack()
tree["columns"] = ("type",)
tree.column("#0", width=300)
tree.column("type", width=100)
tree.heading("#0", text="Name")
tree.heading("type", text="Type")
root_directory = "/path/to/directory" # 替换为您想要显示文件列表的文件夹路径
populate_treeview(root_directory, "")
root.mainloop()
请记得将 “/path/to/directory” 替换为您想要显示文件列表的文件夹路径。