我正在尝试编写一个基本脚本来更新PowerPoint(2016)演示文稿template.pptx,其中包含图像的预定义占位符。我遇到了insert_picture()函数的问题。
例如,template.pptx的第4张幻灯片包含图片占位符:
from pptx import Presentation
prs = Presentation('template.pptx')
slide4 = prs.slides[3]
for shape in slide4.placeholders:
print('%d %s' % (shape.placeholder_format.idx, shape.name))
,它提供以下输出
>>>
0 Title 3
10 Picture Placeholder 7
我继续
placeholder = slide4.placeholders[10] # idx key, not position
picture = placeholder.insert_picture('test.jpg')
会引发以下错误:
File "C:\Python273\lib\site-packages\pptx\shapes\placeholder.py", line 323, in insert_picture
pic = self._new_placeholder_pic(image_file)
File "C:\Python273\lib\site-packages\pptx\shapes\placeholder.py", line 334, in _new_placeholder_pic
rId, desc, image_size = self._get_or_add_image(image_file)
File "C:\Python273\lib\site-packages\pptx\shapes\placeholder.py", line 345, in _get_or_add_image
image_part, rId = self.part.get_or_add_image_part(image_file)
File "C:\Python273\lib\site-packages\pptx\parts\slide.py", line 42, in get_or_add_image_part
image_part = self._package.get_or_add_image_part(image_file)
File "C:\Python273\lib\site-packages\pptx\package.py", line 50, in get_or_add_image_part
return self._image_parts.get_or_add_image_part(image_file)
File "C:\Python273\lib\site-packages\pptx\package.py", line 159, in get_or_add_image_part
image_part = self._find_by_sha1(image.sha1)
File "C:\Python273\lib\site-packages\pptx\package.py", line 171, in _find_by_sha1
if image_part.sha1 == sha1:
AttributeError: 'Part' object has no attribute 'sha1'
我已经看过这个' sha1'这些论坛中提到的错误但并不完全理解(我是一个新手)。
有趣的是(令人沮丧),从头开始创建PowerPoint时我不会遇到这个问题(根据python-pptx 0.6.7文档中的示例):
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[8])
placeholder = slide.placeholders[1] # idx key, not position
picture = placeholder.insert_picture('test.jpg')
prs.save('new.pptx')
这很好,所以我很困惑。任何帮助将非常感激。谢谢!
(Windows 7,Python 2.7.3)
答案 0 :(得分:0)
我已找到此问题的可能原因!对我来说,问题在于演示文稿包含的图像不是jpg,png或gif。这是一个tif文件。对于这些文件,没有sha1,因此脚本会引发异常。转换/删除这些文件使问题消失了!
请告诉我是否也可以解决该问题。