无法使用 Python 在图片占位符 powerpoint 中添加图像

Can't add image in picture placholder powerpoint with Python

我想使用图片占位符自动替换 powerpoint 中的图片

我使用 python 使其动态化,但我遇到如下错误时遇到问题:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'LayoutPlaceholder' object has no attribute 'insert_picture'

我使用的代码如下:

    from pptx import Presentation 
    from pptx.util import Inches
    from PIL import Image
    prs = Presentation(r'..\gambar\base_master_mod.pptx')
    slide = prs.slide_layouts[0]
    placeholder = slide.placeholders[1] # id key, not posisition 
    placeholder.name
    placeholder.placeholder_format.type
    picture = placeholder.insert_picture("..\output_graphics\image_res.png")

这里是我使用的 powerpoint:here

如何解决问题?

将第 5 行更改为:

slide = prs.slides[0]

看看这是否能让你更接近。您可能仍然需要使用占位符 id 来弄清楚它们是什么。你可以做这样的事情来列出它们。

for ph in slide.placeholders:
    print("placeholder %d has name: %s" % (ph.placeholder_format.idx, ph.name)

布局占位符不同于具有不同行为的幻灯片占位符。 .insert_picture() 方法仅适用于幻灯片图片占位符。这就是为什么它说 LayoutPlaceholder has no attribute 'insert_picture'.