最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Python創(chuàng)建多功能文件管理器的代碼示例

 更新時(shí)間:2024年08月05日 10:52:59   作者:winfredzhang  
在本文中,我們將探索一個(gè)使用Python的wxPython庫開發(fā)的文件管理器應(yīng)用程序,這個(gè)應(yīng)用程序不僅能夠?yàn)g覽和選擇文件,還支持文件預(yù)覽、壓縮、圖片轉(zhuǎn)換以及生成PPT演示文稿的功能,需要的朋友可以參考下

簡(jiǎn)介

在本文中,我們將探索一個(gè)使用Python的wxPython庫開發(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"無法為 {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)備

在開始之前,請(qǐng)確保你的Python環(huán)境中已經(jīng)安裝了以下庫:

  • wxPython:用于創(chuàng)建GUI應(yīng)用程序。
  • Pillow:用于圖像處理。
  • python-pptx:用于操作PPT文件。
  • win32com.client:用于處理Excel文件(僅限Windows系統(tǒng))。

可以通過以下命令安裝所需的庫:

pip install wxPython Pillow python-pptx pywin32

應(yīng)用程序結(jié)構(gòu)

我們的文件管理器基于wxPython的框架構(gòu)建,主要分為以下幾個(gè)部分:

  1. 主窗口 (MyFrame 類):包含整個(gè)應(yīng)用程序的布局和控件。
  2. 文件類型選擇:允許用戶根據(jù)文件類型篩選文件。
  3. 文件選擇:使用目錄選擇控件讓用戶選擇要瀏覽的文件夾。
  4. 子文件夾選項(xiàng):一個(gè)復(fù)選框,決定是否包括子文件夾中的文件。
  5. 文件列表和預(yù)覽:展示選中文件夾中的文件,并提供預(yù)覽功能。
  6. 操作按鈕:包括壓縮文件、轉(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è)目錄選擇控件來選擇文件所在的文件夾。

文件列表更新

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)大能力。通過結(jié)合其他庫,我們能夠擴(kuò)展其功能,滿足不同的需求。

結(jié)果如下

結(jié)尾

到此這篇關(guān)于使用Python創(chuàng)建多功能文件管理器的代碼示例的文章就介紹到這了,更多相關(guān)Python創(chuàng)建管理器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

河北省| 囊谦县| 东丽区| 大英县| 桓仁| 虞城县| 乃东县| 竹山县| 阿合奇县| 宜川县| 沅陵县| 财经| 房产| 都安| 邵阳市| 丰原市| 长寿区| 岫岩| 浦城县| 筠连县| 牡丹江市| 肃北| 阿合奇县| 略阳县| 凤阳县| 宁津县| 黔江区| 长兴县| 吕梁市| 大同县| 银川市| 神木县| 洞口县| 昌江| 大田县| 会昌县| 成武县| 本溪市| 蓬安县| 凉城县| 东源县|