You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用python-pptx插入图片时提示SlidePlaceholder无insert_picture属性错误

报错原因

你获取到的placeholders[2]为通用SlidePlaceholder类型,该类未提供insert_picture方法,因此调用时抛出属性不存在的错误。

解决方案

有两种常用修复方式,推荐使用第二种兼容性更强:

方案1:确认占位符类型后调用插入方法

如果你确认当前布局索引3对应的第3个占位符为图片/内容占位符,仅需调整插入代码的写法即可:
将原代码中

self.slide.placeholders[2].insert_picture(data[2])

替换为:

content_placeholder = self.slide.placeholders[2]
content_placeholder.insert_picture(data[2])

方案2:替换占位符为对应尺寸图片(兼容性更强)

如果不确定占位符类型,可以先获取占位符的位置、尺寸参数,删除原占位符后直接插入对应大小的图片,不受占位符类型限制:

if data[2] != "":
    placeholder = self.slide.placeholders[2]
    # 记录占位符的位置与尺寸
    left, top = placeholder.left, placeholder.top
    width, height = placeholder.width, placeholder.height
    # 移除原占位符
    placeholder._sp.getparent().remove(placeholder._sp)
    # 插入适配尺寸的图片
    self.slide.shapes.add_picture(data[2], left, top, width=width, height=height)
额外注意

请保证图片文件girl.png和运行的Python脚本在同一目录下,否则需要传入图片的绝对路径,避免触发文件不存在的报错。

修改后完整可运行代码
from pptx import Presentation
import os

prs = Presentation()

class Myslide:
    def __init__(self, data):
        self.layout = prs.slide_layouts[data[3]]
        self.slide=prs.slides.add_slide(self.layout)
        self.title=self.slide.shapes.title
        self.title.text=data[0]
        self.subtitle=self.slide.placeholders[1]
        self.subtitle.text=data[1]
        if data[2] != "":
            placeholder = self.slide.placeholders[2]
            left, top = placeholder.left, placeholder.top
            width, height = placeholder.width, placeholder.height
            placeholder._sp.getparent().remove(placeholder._sp)
            self.slide.shapes.add_picture(data[2], left, top, width=width, height=height)

slides = [
    ["USA Weather",       #data[0]
     "Subtitle(Bullet)",
     "girl.png",
     3],
    ["Malaysia Weather",       #data[0]
     "Content(Bullet)",
     "",
     3],
    ["China Weather",       #data[0]
     "This is a brown Fox",
     "",
     3]
]

for es in slides:
    Myslide(es)

prs.save('test.pptx')
os.startfile("test.pptx")

内容的提问来源于stack exchange,提问作者Naina Yadav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 18:36:03