简介
在本文中,我们将探索一个使用python的wxpython库开发的文件管理器应用程序。这个应用程序不仅能够浏览和选择文件,还支持文件预览、压缩、图片转换以及生成ppt演示文稿的功能。
c:\pythoncode\new\filemanager.py
完整代码
import wx
import os
import zipfile
from pil import imagegrab, image
from pptx import presentation
import win32com.client
class myframe(wx.frame):
def __init__(self):
super().__init__(parent=none, title="文件管理器", size=(800, 600))
self.panel = wx.panel(self)
# 布局
self.main_sizer = wx.boxsizer(wx.vertical)
self.top_sizer = wx.boxsizer(wx.horizontal)
self.mid_sizer = wx.boxsizer(wx.horizontal)
self.listbox_sizer = wx.boxsizer(wx.vertical)
self.preview_sizer = wx.boxsizer(wx.vertical)
self.bottom_sizer = wx.boxsizer(wx.horizontal)
# 文件类型选择
self.file_type_choice = wx.choice(self.panel, choices=["照片", "word", "excel", "ppt", "pdf"])
self.file_type_choice.bind(wx.evt_choice, self.on_file_type_selected)
self.top_sizer.add(self.file_type_choice, 1, wx.expand | wx.all, 5)
# 文件选择
self.dir_picker = wx.dirpickerctrl(self.panel, message="选择文件夹")
self.dir_picker.bind(wx.evt_dirpicker_changed, self.on_dir_picked)
self.top_sizer.add(self.dir_picker, 1, wx.expand | wx.all, 5)
# 包含子文件夹复选框
self.include_subfolders_checkbox = wx.checkbox(self.panel, label="包含子文件夹")
self.include_subfolders_checkbox.bind(wx.evt_checkbox, self.on_include_subfolders_checked)
self.top_sizer.add(self.include_subfolders_checkbox, 0, wx.align_center_vertical | wx.all, 5)
# 分割器
self.splitter = wx.splitterwindow(self.panel)
self.splitter.bind(wx.evt_splitter_dclick, self.on_splitter_dclick)
self.left_panel = wx.panel(self.splitter)
self.right_panel = wx.panel(self.splitter)
# 文件列表
self.file_listbox = wx.listbox(self.left_panel, style=wx.lb_multiple, size=(400, -1))
self.file_listbox.bind(wx.evt_listbox, self.on_file_selected)
self.file_listbox.bind(wx.evt_listbox_dclick, self.on_file_deselected)
self.file_listbox.bind(wx.evt_listbox, self.on_drag_select)
self.listbox_sizer.add(self.file_listbox, 1, wx.expand | wx.all, 5)
# 全选和全不选按钮
self.select_all_button = wx.button(self.left_panel, label="全选")
self.select_all_button.bind(wx.evt_button, self.on_select_all)
self.deselect_all_button = wx.button(self.left_panel, label="全不选")
self.deselect_all_button.bind(wx.evt_button, self.on_deselect_all)
self.listbox_sizer.add(self.select_all_button, 0, wx.expand | wx.all, 5)
self.listbox_sizer.add(self.deselect_all_button, 0, wx.expand | wx.all, 5)
# 设置左侧面板布局
self.left_panel.setsizer(self.listbox_sizer)
# 预览窗口
self.preview_panel = wx.panel(self.right_panel, size=(400, 400))
self.preview_sizer = wx.boxsizer(wx.vertical)
self.preview_panel.setsizer(self.preview_sizer)
# self.preview_panel = wx.panel(self.right_panel, size=(400, 400))
# self.preview_panel.setsizer(self.preview_sizer)
# self.right_panel.setsizer(self.preview_sizer)
# 设置分割器布局
self.splitter.splitvertically(self.left_panel, self.right_panel)
self.splitter.setsashgravity(0.5)
self.splitter.setminimumpanesize(100)
self.mid_sizer.add(self.splitter, 1, wx.expand | wx.all, 5)
# 操作按钮
self.zip_button = wx.button(self.panel, label="压缩")
self.zip_button.bind(wx.evt_button, self.on_zip)
self.convert_button = wx.button(self.panel, label="转换图片")
self.convert_button.bind(wx.evt_button, self.on_convert)
self.generate_ppt_button = wx.button(self.panel, label="生成ppt文档")
self.generate_ppt_button.bind(wx.evt_button, self.on_generate_ppt)
self.bottom_sizer.add(self.zip_button, 1, wx.expand | wx.all, 5)
self.bottom_sizer.add(self.convert_button, 1, wx.expand | wx.all, 5)
self.bottom_sizer.add(self.generate_ppt_button, 1, wx.expand | wx.all, 5)
# 整体布局
self.main_sizer.add(self.top_sizer, 0, wx.expand)
self.main_sizer.add(self.mid_sizer, 1, wx.expand)
self.main_sizer.add(self.bottom_sizer, 0, wx.expand)
self.panel.setsizer(self.main_sizer)
self.show()
def on_dir_picked(self, event):
self.dir_path = self.dir_picker.getpath()
self.update_file_list()
def on_file_type_selected(self, event):
self.file_type = self.file_type_choice.getstringselection()
self.update_file_list()
def on_include_subfolders_checked(self, event):
self.update_file_list()
def update_file_list(self):
if hasattr(self, 'dir_path') and hasattr(self, 'file_type'):
self.file_listbox.clear()
include_subfolders = self.include_subfolders_checkbox.getvalue()
for root, dirs, files in os.walk(self.dir_path):
if not include_subfolders and root != self.dir_path:
continue
for file in files:
if self.file_type == "照片" and file.lower().endswith(('png', 'jpg', 'jpeg')):
self.file_listbox.append(os.path.join(root, file))
elif self.file_type == "word" and file.lower().endswith('docx'):
self.file_listbox.append(os.path.join(root, file))
elif self.file_type == "excel" and file.lower().endswith('xlsx'):
self.file_listbox.append(os.path.join(root, file))
elif self.file_type == "ppt" and file.lower().endswith('pptx'):
self.file_listbox.append(os.path.join(root, file))
elif self.file_type == "pdf" and file.lower().endswith('pdf'):
self.file_listbox.append(os.path.join(root, file))
def on_file_selected(self, event):
selections = self.file_listbox.getselections()
if selections:
file_path = self.file_listbox.getstring(selections[0])
self.preview_file(file_path)
def on_file_deselected(self, event):
# 单击文件名时,取消选择
event.skip()
def on_drag_select(self, event):
selections = self.file_listbox.getselections()
if selections:
file_path = self.file_listbox.getstring(selections[0])
self.preview_file(file_path)
def on_select_all(self, event):
count = self.file_listbox.getcount()
for i in range(count):
self.file_listbox.select(i)
def on_deselect_all(self, event):
count = self.file_listbox.getcount()
for i in range(count):
self.file_listbox.deselect(i)
def preview_file(self, file_path):
# clear any existing content in the preview panel
for child in self.preview_panel.getchildren():
child.destroy()
if file_path.lower().endswith(('png', 'jpg', 'jpeg')):
try:
original_image = wx.image(file_path, wx.bitmap_type_any)
# get the size of the preview panel
panel_size = self.preview_panel.getsize()
# calculate the scaling factor to fit the image within the panel
width_ratio = panel_size.width / original_image.getwidth()
height_ratio = panel_size.height / original_image.getheight()
scale_factor = min(width_ratio, height_ratio)
# scale the image
new_width = int(original_image.getwidth() * scale_factor)
new_height = int(original_image.getheight() * scale_factor)
image = original_image.scale(new_width, new_height, wx.image_quality_high)
bitmap = wx.bitmap(image)
static_bitmap = wx.staticbitmap(self.preview_panel, -1, bitmap)
self.preview_sizer.add(static_bitmap, 0, wx.center)
except exception as e:
print(f"error loading image: {e}")
# other file types preview implementation can be added here
self.preview_panel.layout()
self.right_panel.layout()
def on_zip(self, event):
file_paths = [self.file_listbox.getstring(i) for i in self.file_listbox.getselections()]
with zipfile.zipfile(os.path.join(self.dir_path, 'compressed_files.zip'), 'w') as zipf:
for file_path in file_paths:
zipf.write(file_path, os.path.basename(file_path))
def on_convert(self, event):
file_paths = [self.file_listbox.getstring(i) for i in self.file_listbox.getselections()]
self.process_files(file_paths)
def process_files(self, file_paths):
excel = win32com.client.dispatch("excel.application")
excel.visible = false
for file_path in file_paths:
try:
workbook = excel.workbooks.open(file_path)
sheet = workbook.sheets(1)
# 获取工作表的使用范围
used_range = sheet.usedrange
# 设置截图区域
sheet.range(used_range.address).copypicture(format=2) # 2 表示位图
# 创建一个临时图片对象并粘贴截图
img = imagegrab.grabclipboard()
if img:
# 保存截图
base_name = os.path.splitext(file_path)[0]
img_path = f"{base_name}_screenshot.png"
img.save(img_path)
print(f"截图已保存: {img_path}")
else:
print(f"无法为 {file_path} 创建截图")
workbook.close(savechanges=false)
except exception as e:
print(f"处理 {file_path} 时出错: {str(e)}")
excel.quit()
wx.messagebox("所有文件处理完成", "完成", wx.ok | wx.icon_information)
def on_generate_ppt(self, event):
file_paths = [self.file_listbox.getstring(i) for i in self.file_listbox.getselections()]
prs = presentation()
for file_path in file_paths:
if file_path.lower().endswith(('png', 'jpg', 'jpeg')):
slide = prs.slides.add_slide(prs.slide_layouts[5])
img_path = file_path
slide.shapes.add_picture(img_path, 0, 0, prs.slide_width, prs.slide_height)
prs.save(os.path.join(self.dir_path, 'output_ppt.pptx'))
def on_splitter_dclick(self, event):
self.splitter.unsplit()
def on_drag_select(self, event):
selections = self.file_listbox.getselections()
if selections:
file_path = self.file_listbox.getstring(selections[0])
self.preview_file(file_path)
if __name__ == '__main__':
app = wx.app(false)
frame = myframe()
app.mainloop()
环境准备
在开始之前,请确保你的python环境中已经安装了以下库:
- wxpython:用于创建gui应用程序。
- pillow:用于图像处理。
- python-pptx:用于操作ppt文件。
- win32com.client:用于处理excel文件(仅限windows系统)。
可以通过以下命令安装所需的库:
pip install wxpython pillow python-pptx pywin32
应用程序结构
我们的文件管理器基于wxpython的框架构建,主要分为以下几个部分:
- 主窗口 (
myframe类):包含整个应用程序的布局和控件。 - 文件类型选择:允许用户根据文件类型筛选文件。
- 文件选择:使用目录选择控件让用户选择要浏览的文件夹。
- 子文件夹选项:一个复选框,决定是否包括子文件夹中的文件。
- 文件列表和预览:展示选中文件夹中的文件,并提供预览功能。
- 操作按钮:包括压缩文件、转换图片和生成ppt文档的功能。
代码解析
初始化和布局设置
class myframe(wx.frame):
def __init__(self):
super().__init__(parent=none, title="文件管理器", size=(800, 600))
# 初始化窗口、面板、大小器等
# ...
文件类型选择和目录选择
self.file_type_choice = wx.choice(self.panel, choices=["照片", "word", "excel", "ppt", "pdf"]) self.dir_picker = wx.dirpickerctrl(self.panel, message="选择文件夹")
这里创建了一个下拉菜单供用户选择文件类型,以及一个目录选择控件来选择文件所在的文件夹。
文件列表更新
def update_file_list(self):
# 根据选择的目录和文件类型更新文件列表
# ...
文件预览
def preview_file(self, file_path):
# 根据文件类型显示预览
# ...
压缩文件
def on_zip(self, event):
# 将选中的文件压缩成一个zip文件
# ...
转换图片
def on_convert(self, event):
# 将excel文件转换为图片
# ...
生成ppt文档
def on_generate_ppt(self, event):
# 使用选中的图片生成ppt文档
# ...
总结
这个文件管理器应用程序是一个功能丰富的工具,它展示了wxpython在创建桌面应用程序方面的强大能力。通过结合其他库,我们能够扩展其功能,满足不同的需求。
结果如下

结尾
到此这篇关于使用python创建多功能文件管理器的代码示例的文章就介绍到这了,更多相关python创建管理器内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论