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

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

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

簡介

在本文中,我們將探索一個使用Python的wxPython庫開發(fā)的文件管理器應用程序。這個應用程序不僅能夠瀏覽和選擇文件,還支持文件預覽、壓縮、圖片轉換以及生成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
                
                # 設置截圖區(qū)域
                sheet.Range(used_range.Address).CopyPicture(Format=2)  # 2 表示位圖
                
                # 創(chuàng)建一個臨時圖片對象并粘貼截圖
                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} 時出錯: {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)境準備

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

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

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

pip install wxPython Pillow python-pptx pywin32

應用程序結構

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

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

這里創(chuàng)建了一個下拉菜單供用戶選擇文件類型,以及一個目錄選擇控件來選擇文件所在的文件夾。

文件列表更新

def update_file_list(self):
    # 根據(jù)選擇的目錄和文件類型更新文件列表
    # ...

文件預覽

def preview_file(self, file_path):
    # 根據(jù)文件類型顯示預覽
    # ...

壓縮文件

def on_zip(self, event):
    # 將選中的文件壓縮成一個ZIP文件
    # ...

轉換圖片

def on_convert(self, event):
    # 將Excel文件轉換為圖片
    # ...

生成PPT文檔

def on_generate_ppt(self, event):
    # 使用選中的圖片生成PPT文檔
    # ...

總結

這個文件管理器應用程序是一個功能豐富的工具,它展示了wxPython在創(chuàng)建桌面應用程序方面的強大能力。通過結合其他庫,我們能夠擴展其功能,滿足不同的需求。

結果如下

結尾

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

相關文章

  • 圖像檢索之基于vlfeat實現(xiàn)SIFT特征

    圖像檢索之基于vlfeat實現(xiàn)SIFT特征

    SIFT特征的講解已經(jīng)很多了,本文就借助vlfeat對SIFT特征的提取過程做一個總結。接下來通過本文給大家介紹圖像檢索之基于vlfeat實現(xiàn)SIFT,感興趣的朋友跟隨小編一起看看吧
    2021-12-12
  • python+numpy+matplotalib實現(xiàn)梯度下降法

    python+numpy+matplotalib實現(xiàn)梯度下降法

    這篇文章主要為大家詳細介紹了python+numpy+matplotalib實現(xiàn)梯度下降法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-08-08
  • Python 動態(tài)變量名定義與調用方法

    Python 動態(tài)變量名定義與調用方法

    這篇文章主要介紹了Python 動態(tài)變量名定義與調用方法,需要的朋友可以參考下
    2020-02-02
  • 用Python生成藝術之分形與算法繪圖實踐

    用Python生成藝術之分形與算法繪圖實踐

    這篇文章主要介紹了用Python生成藝術之分形與算法繪圖實踐,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2026-03-03
  • python爬蟲之BeautifulSoup 使用select方法詳解

    python爬蟲之BeautifulSoup 使用select方法詳解

    本篇文章主要介紹了python爬蟲之BeautifulSoup 使用select方法詳解,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-10-10
  • Python 的 __str__ 和 __repr__ 方法對比

    Python 的 __str__ 和 __repr__ 方法對比

    這篇文章主要介紹了Python 的 __str__ 和 __repr__ 方法的相關資料,幫助大家區(qū)分__str__ 和 __repr__ ,感興趣的朋友可以了解下
    2020-09-09
  • Python表示當前時間的方法合集

    Python表示當前時間的方法合集

    在 Python 中獲取當前時間是許多與時間有關的操作的一個很好的起點。一個非常重要的用例是創(chuàng)建時間戳。在本教程中,你將學習如何用 datetime 模塊獲取、顯示和格式化當前時間
    2023-01-01
  • python爬蟲開發(fā)之selenium模塊詳細使用方法與實例全解

    python爬蟲開發(fā)之selenium模塊詳細使用方法與實例全解

    這篇文章主要介紹了python爬蟲開發(fā)之selenium模塊詳細使用方法與實例全解,selenium模塊詳細在爬蟲開發(fā)中主要用來解決JavaScript渲染問題需要的朋友可以參考下
    2020-03-03
  • Python命令行解析器argparse詳解

    Python命令行解析器argparse詳解

    大家好,本篇文章主要講的是Python命令行解析器argparse詳解,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2022-01-01
  • 解決json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)錯誤

    解決json.decoder.JSONDecodeError: Expecting value:&n

    這篇文章主要介紹了解決json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)錯誤,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-04-04

最新評論

鄂尔多斯市| 清远市| 渭南市| 增城市| 方山县| 仙游县| 江北区| 石阡县| 体育| 台东市| 武陟县| 闸北区| 三河市| 阿勒泰市| 拉孜县| 夏河县| 天门市| 方山县| 永福县| 外汇| 德州市| 易门县| 博白县| 溧水县| 崇阳县| 铜梁县| 积石山| 左权县| 偃师市| 荆州市| 始兴县| 莱芜市| 罗江县| 天峨县| 马山县| 金昌市| 抚顺县| 桃园县| 石渠县| 尉氏县| 临漳县|