我想使用 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/