Python-pptx : issue with insert_picture() function - 'sha1' AttributeError

标签 python python-2.7

我正在尝试编写一个基本脚本来更新 PowerPoint (2016) 演示文稿 template.pptx,其中包含图像的预定义占位符。我遇到了 insert_picture() 函数的问题。

例如,template.pptx 的第四张幻灯片包含图片占位符:

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)

最佳答案

我已经找到了这个问题的可能原因!对我来说,问题是演示文稿中包含的图像不是 jpg、png 或 gif 格式的。这是一个 tif 文件。对于这些文件,没有 sha1,因此脚本会引发异常。转换/删除这些文件使问题消失!

请告诉我这是否也适合您。

关于Python-pptx : issue with insert_picture() function - 'sha1' AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49357270/

相关文章:

flask 中的 python 装饰器

Python解析CSV忽略带双引号的逗号

python - SqlAlchemy 当前数据库用户

python - 比较 pandas 数据框中的两列以创建第三列

python - 在 Python 中使用 Rasterbar libtorrent 进行樱桃选择

python - 在 flask 中开始 celery : AttributeError: 'Flask' object has no attribute 'user_options'

python - 在 python 中更改字典

python-2.7 - 根据类型或类别列出 Microsoft Azure 计算中的 VM 大小

Python deepcopy ..有点

python - 在 tar gzip 文件中逐行解析 gzip 日志文件