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

时间:2019-06-05 19:34:00

标签: python powerpoint python-pptx

我想用var client = new SessionsClientBuilder { CredentialsPath = "path to file", }.Build(); 将我创建的图插入到功率点中。
我从网上搜索,发现了信息here

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

insert_picture()

然后我使用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')

我发现了一个here字条。

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

之后,我将代码更改为:

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

有什么主意吗?

1 个答案:

答案 0 :(得分:0)

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

fig.save('test')

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