用python写一个类似windows资源管理器的程序
时间: 2023-10-16 07:08:17 浏览: 60
当然可以!以下是一个简单的示例,使用Python的tkinter库创建一个类似Windows资源管理器的程序:
```python
import os
import tkinter as tk
from tkinter import ttk, messagebox
class FileExplorer:
def __init__(self, root):
self.root = root
self.root.title("文件资源管理器")
# 创建目录树
self.tree = ttk.Treeview(self.root)
self.tree.pack(side="left", fill="y")
self.tree.bind("<Double-1>", self.on_double_click)
# 创建滚动条
scrollbar = ttk.Scrollbar(self.root, orient="vertical", command=self.tree.yview)
scrollbar.pack(side="right", fill="y")
self.tree.configure(yscrollcommand=scrollbar.set)
# 加载系统根目录
for drive in self.get_drives():
self.tree.insert("", "end", text=drive, open=False)
def get_drives(self):
drives = []
for drive in range(ord("A"), ord("Z")+1):
drive = chr(drive)
if os.path.exists(drive + ":\\"):
drives.append(drive + ":\\")
return drives
def get_files(self, directory):
files = []
for item in os.listdir(directory):
item_path = os.path.join(directory, item)
if os.path.isfile(item_path):
files.append(item)
return files
def on_double_click(self, event):
item = self.tree.selection()[0]
directory = self.tree.item(item, "text")
if not os.path.exists(directory):
messagebox.showerror("错误", "路径不存在!")
return
if not os.path.isdir(directory):
messagebox.showerror("错误", "不是一个有效的目录!")
return
for child in self.tree.get_children(item):
self.tree.delete(child)
for file in self.get_files(directory):
self.tree.insert(item, "end", text=file, open=False)
root = tk.Tk()
app = FileExplorer(root)
root.mainloop()
```
运行以上代码,将会弹出一个窗口,显示系统的根目录。双击目录将展开该目录下的文件。请注意,此示例仅包含基本功能,您可以根据需要进行扩展和定制。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)