您可以按照以下步驟使用 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” 替換為您想要顯示文件列表的文件夾路徑。