在这篇博客中,我们将学习如何使用Python将Word文档中的图片提取出来并生成一个PowerPoint幻灯片。我们将借助wxPython、python-docx和python-pptx这三个强大的库来实现这一目标。以下是实现这个功能的完整过程。
C:\pythoncode\new\wordTOppt.py
所需库
首先,我们需要安装以下Python库:
- wxPython:用于创建图形用户界面(GUI)。
- python-docx:用于处理Word文档。
- python-pptx:用于生成PowerPoint幻灯片。
你可以通过以下命令安装这些库:
pip install wxPython python-docx python-pptx
创建GUI
我们将使用wxPython创建一个简单的GUI,让用户选择一个Word文档,并点击按钮来执行图片提取和PPT生成的过程。以下是实现这个功能的代码:
import wx
import os
import docx
from pptx import Presentation
from pptx.util import Inches, Pt
class MyFrame(wx.Frame):
def __init__(self, parent, title):
super(MyFrame, self).__init__(parent, title=title, size=(600, 300))
self.panel = wx.Panel(self)
self.create_widgets()
def create_widgets(self):
vbox = wx.BoxSizer(wx.VERTICAL)
self.file_picker = wx.FilePickerCtrl(self.panel, message="选择 Word 文档", wildcard="Word files (*.docx)|*.docx")
vbox.Add(self.file_picker, 0, wx.ALL | wx.EXPAND, 5)
self.extract_button = wx.Button(self.panel, label="提取并生成幻灯片")
self.extract_button.Bind(wx.EVT_BUTTON, self.on_extract)
vbox.Add(self.extract_button, 0, wx.ALL | wx.EXPAND, 5)
self.panel.SetSizer(vbox)
def on_extract(self, event):
word_file_path = self.file_picker.GetPath()
if not os.path.exists(word_file_path):
wx.MessageBox("文件未找到!", "错误", wx.OK | wx.ICON_ERROR)
return
# Create images directory to store extracted images
images_dir = os.path.join(os.path.dirname(word_file_path), 'images')
if not os.path.exists(images_dir):
os.makedirs(images_dir)
# Extract images from Word document
try:
doc = docx.Document(word_file_path)
for r_id, rel in doc.part.rels.items