python-pptx:将图片插入占位符但出现错误

标签 python powerpoint python-pptx

我想使用 insert_picture() 将我创建的绘图插入到幻灯片中。
我从网上搜索,找到信息here

我创建了一个简单的图形,如下所示:

fig, ax = plt.subplots(2,1, sharex=True, sharey=True)

我使用 python-pptx 创建一个幻灯片。

graph_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(graph_slide_layout)
title = slide.shapes.title
title.text = "Test"
placeholder = slide.placeholders[1]
pic = placeholder.insert_picture(fig)
prs.save('Desktop\test.pptx')

但是,我收到一个错误:

AttributeError: 'SlidePlaceholder' object has no attribute 'insert_picture'

我发现了一张纸条 here

Note
A reference to a picture placeholder becomes invalid after its insert_picture() method is called. 
This is because the process of inserting a picture replaces the original p:sp XML element with a new p:pic element containing the picture. 
Any attempt to use the original placeholder reference after the call will raise AttributeError. 
The new placeholder is the return value of the insert_picture() call and may also be obtained from the placeholders collection using the same idx key.

之后,我将代码更改为:

graph_slide_layout = prs.slide_layouts[8]
slide = prs.slides.add_slide(graph_slide_layout)
title = slide.shapes.title
title.text = "Test"
placeholder = slide.placeholders[1]
pic = placeholder.insert_picture(fig)
prs.save('Desktop\test.pptx')

placeholder.name
'Picture Placeholder 2'
placeholder.placeholder_format.type
18

我收到另一个错误:

AttributeError: 'Figure' object has no attribute 'seek'

有什么想法吗?

最佳答案

我解决了。
您应该首先保存图形并使用保存图。

fig.save('test')

pic = placeholder.insert_picture('test.png')

关于python-pptx:将图片插入占位符但出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56466896/

相关文章:

python - 在 Pandas 中将一个时间序列插值到另一个时间序列

vba - PowerPoint VBA : Copy and paste image, 对齐到中心,并拉伸(stretch)以适合页面

python - 如何使用 Python 生成包含在 PowerPoint 布局上定义的图表的幻灯片?

powerpoint - 您可以使用 python-pptx 更改占位符类型吗?

Python 多个用户同时追加到同一个文件

python - mypy "is not valid as a type"对于使用 `type()` 构造的类型

python - 我如何让 Mypy 意识到 isinstance 已经被调用了?

powerpoint - 将Powerpoint查看器嵌入网页(PHP)

c# - 使用c#实现activeX控件在Windows窗体中查看PowerPoint幻灯片,不显示控件

python - 如何使用 pptx python 库更改 PPT 幻灯片上项目符号列表的缩进