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

使用Python-pptx创建双内容幻灯片布局遇KeyError报错求助

问题原因及解决方法

问题根源

你选的slide_layouts[5]是标题+图片布局,根本没有索引为1、2的内容占位符,所以触发KeyError。默认空白演示文稿的布局索引里,双栏内容布局的索引是3(索引从0开始计数)。

另外直接用数字索引占位符容易踩坑,建议通过占位符名称或类型定位更可靠。

修复后的代码

from pptx import Presentation

# 创建演示文稿实例
prs = Presentation()
# 选择双栏内容布局(对应索引3)
slide_layout = prs.slide_layouts[3]
slide = prs.slides.add_slide(slide_layout)

# 设置幻灯片标题(标题占位符索引通常为0)
title_placeholder = slide.placeholders[0]
title_placeholder.text = "双内容分栏演示"

# 设置左右分栏的内容
left_content = slide.placeholders[1]
left_content.text = "左侧内容区域"
right_content = slide.placeholders[2]
right_content.text = "右侧内容区域"

prs.save('双内容幻灯片.pptx')
print("演示文稿创建成功")

避坑小技巧

如果不确定占位符的索引或用途,可以先打印当前幻灯片的所有占位符信息,精准定位:

from pptx import Presentation

prs = Presentation()
slide_layout = prs.slide_layouts[3]
slide = prs.slides.add_slide(slide_layout)

# 遍历打印所有占位符的索引、名称和类型
for idx, placeholder in enumerate(slide.placeholders):
    print(f"索引: {idx}, 名称: {placeholder.name}, 类型: {placeholder.placeholder_type}")

内容的提问来源于stack exchange,提问作者Khizer Tariq

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:52:20