python-pptx: вставить изображение в заполнитель, но получить ошибку - PullRequest
1 голос
/ 05 июня 2019

Я хочу вставить созданный мной график в точку питания с помощью 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')

Однако я получил ошибку:

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

Я получил еще одну ошибку:

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

Есть идеи?

1 Ответ

0 голосов
/ 05 июня 2019

Я решил.
Вы должны сначала сохранить фигуру и использовать график сохранения.

fig.save('test')

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