2
votes

I apologize, I have been looking for a solution but can't find enough documentation to figure it out. I am trying to import a default slide layout required for school, it has a special background and a Title Block and a Subtitle Block. I assumed when I import this, python-pptx would just automatically create placeholders 0 and 1 for those two text blocks but when I try and edit the placeholders, I get an attribute error:

AttributeError: 'Presentation' object has no attribute 'placeholders'

My code is as follows:

from pptx import Presentation
prs = Presentation('SeniorDesignTitleSlide.pptx')

Presentation_Title = prs.placeholders[0]
Presentation_Subtitle = prs.placeholders[1]
Presentation_Title.text = 'This Is a Test'
Presentation_Subtitle.text = 'Is This Working?'

prs.save('SlideLayoutImportTest.pptx')

Edit[0]: I do realize I am just opening that particular presentation, but how do I access and edit the single slide that’s in it ?

Edit[1]: I’ve found a few posts from 2015 about python-pptx expanding on this feature, but there’s no further information that it actually occurred.

How does python-pptx assign placeholders for imported slide layouts? Or does it even do this? Does it need to be a .potx file?

Thank you in advance.

1

1 Answers

8
votes

Placeholders belong to a slide object, not a presentation object. So the first thing is to get ahold of a slide.

A slide is created from a slide layout, which it essentially clones to get some starting shapes, including placeholders in many cases.

So the first step is to figure out which slide layout you want. The easiest way to do this is to open the "starting" presentation (sometimes called a "template" presentation) and inspect it's slide master and layouts using the View > Master > Slide Master... menu option.

Find the one you want, count down to it from the first layout, starting at 0, and that gives you the index of that slide layout.

Then your code looks something like this:

from pptx import Presentation

prs = Presentation('SeniorDesignTitleSlide.pptx')

slide_layout = prs.slide_layouts[0]  # assuming you want the first one
slide = prs.slides.add_slide(slide_layout)

Presentation_Title = slide.placeholders[0]
Presentation_Subtitle = slide.placeholders[1]
Presentation_Title.text = 'This Is a Test'
Presentation_Subtitle.text = 'Is This Working?'

prs.save('SlideLayoutImportTest.pptx')

The placeholders collection behaves like a dict as far as indexed access goes, so the 0 and 1 used as indices above are unlikely to match exactly in your case (although the 0 will probably work; the title is always 0).

This page of the documentation explains how to discover what indices your template has available: http://python-pptx.readthedocs.io/en/latest/user/placeholders-using.html

The page before that one has more on placeholder concepts: http://python-pptx.readthedocs.io/en/latest/user/placeholders-understanding.html