使用Python創(chuàng)建多功能文件管理器的代碼示例
簡(jiǎn)介
在本文中,我們將探索一個(gè)使用Python的wxPython庫(kù)開(kāi)發(fā)的文件管理器應(yīng)用程序。這個(gè)應(yīng)用程序不僅能夠?yàn)g覽和選擇文件,還支持文件預(yù)覽、壓縮、圖片轉(zhuǎn)換以及生成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)
# 包含子文件夾復(fù)選框
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)
# 設(shè)置左側(cè)面板布局
self.left_panel.SetSizer(self.listbox_sizer)
# 預(yù)覽窗口
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)
# 設(shè)置分割器布局
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="轉(zhuǎn)換圖片")
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):
# 單擊文件名時(shí),取消選擇
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
# 設(shè)置截圖區(qū)域
sheet.Range(used_range.Address).CopyPicture(Format=2) # 2 表示位圖
# 創(chuàng)建一個(gè)臨時(shí)圖片對(duì)象并粘貼截圖
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"無(wú)法為 {file_path} 創(chuàng)建截圖")
workbook.Close(SaveChanges=False)
except Exception as e:
print(f"處理 {file_path} 時(shí)出錯(cuò): {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()
環(huán)境準(zhǔn)備
在開(kāi)始之前,請(qǐng)確保你的Python環(huán)境中已經(jīng)安裝了以下庫(kù):
- wxPython:用于創(chuàng)建GUI應(yīng)用程序。
- Pillow:用于圖像處理。
- python-pptx:用于操作PPT文件。
- win32com.client:用于處理Excel文件(僅限Windows系統(tǒng))。
可以通過(guò)以下命令安裝所需的庫(kù):
pip install wxPython Pillow python-pptx pywin32
應(yīng)用程序結(jié)構(gòu)
我們的文件管理器基于wxPython的框架構(gòu)建,主要分為以下幾個(gè)部分:
- 主窗口 (
MyFrame類):包含整個(gè)應(yīng)用程序的布局和控件。 - 文件類型選擇:允許用戶根據(jù)文件類型篩選文件。
- 文件選擇:使用目錄選擇控件讓用戶選擇要瀏覽的文件夾。
- 子文件夾選項(xiàng):一個(gè)復(fù)選框,決定是否包括子文件夾中的文件。
- 文件列表和預(yù)覽:展示選中文件夾中的文件,并提供預(yù)覽功能。
- 操作按鈕:包括壓縮文件、轉(zhuǎn)換圖片和生成PPT文檔的功能。
代碼解析
初始化和布局設(shè)置
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="選擇文件夾")
這里創(chuàng)建了一個(gè)下拉菜單供用戶選擇文件類型,以及一個(gè)目錄選擇控件來(lái)選擇文件所在的文件夾。
文件列表更新
def update_file_list(self):
# 根據(jù)選擇的目錄和文件類型更新文件列表
# ...
文件預(yù)覽
def preview_file(self, file_path):
# 根據(jù)文件類型顯示預(yù)覽
# ...
壓縮文件
def on_zip(self, event):
# 將選中的文件壓縮成一個(gè)ZIP文件
# ...
轉(zhuǎn)換圖片
def on_convert(self, event):
# 將Excel文件轉(zhuǎn)換為圖片
# ...
生成PPT文檔
def on_generate_ppt(self, event):
# 使用選中的圖片生成PPT文檔
# ...
總結(jié)
這個(gè)文件管理器應(yīng)用程序是一個(gè)功能豐富的工具,它展示了wxPython在創(chuàng)建桌面應(yīng)用程序方面的強(qiáng)大能力。通過(guò)結(jié)合其他庫(kù),我們能夠擴(kuò)展其功能,滿足不同的需求。
結(jié)果如下

結(jié)尾
到此這篇關(guān)于使用Python創(chuàng)建多功能文件管理器的代碼示例的文章就介紹到這了,更多相關(guān)Python創(chuàng)建管理器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于反爬蟲(chóng)的一些簡(jiǎn)單總結(jié)
這篇文章主要介紹了關(guān)于反爬蟲(chóng)的一些簡(jiǎn)單總結(jié),具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12
Boston數(shù)據(jù)集預(yù)測(cè)放假及應(yīng)用優(yōu)缺點(diǎn)評(píng)估
這篇文章主要為大家介紹了Boston數(shù)據(jù)集預(yù)測(cè)放假及應(yīng)用優(yōu)缺點(diǎn)評(píng)估,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10
基于python+opencv調(diào)用電腦攝像頭實(shí)現(xiàn)實(shí)時(shí)人臉眼睛以及微笑識(shí)別
這篇文章主要為大家詳細(xì)介紹了基于python+opencv調(diào)用電腦攝像頭實(shí)現(xiàn)實(shí)時(shí)人臉眼睛以及微笑識(shí)別,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
python數(shù)據(jù)分析基礎(chǔ)之pandas中l(wèi)oc()與iloc()的介紹與區(qū)別介紹
我們經(jīng)常在尋找數(shù)據(jù)的某行或者某列的時(shí)常用到Pandas中的兩種方法iloc和loc,兩種方法都接收兩個(gè)參數(shù),第一個(gè)參數(shù)是行的范圍,第二個(gè)參數(shù)是列的范圍,這篇文章主要介紹了python數(shù)據(jù)分析基礎(chǔ)之pandas中l(wèi)oc()與iloc()的介紹與區(qū)別,需要的朋友可以參考下2024-07-07

