Python-PPTX: KeyError: 'no placeholder on this slide with idx == 1'

谁说胖子不能爱 提交于 2020-01-16 08:40:16

问题


I am trying to use an existing powerpoint presentation as a template and then insert my slides in the same.

I am not concerned about the existing slides in the presentation and i would like to delete them (I haven't planned how yet), but i am more focused that the new slides created will have the same font and color scheme as the existing ones.

Below is my code:

prs = Presentation('UNTITLED.pptx')
slide_master = prs.slide_master

def add_slide(prs, layout, title, data1, data2):
    """Return slide newly added to `prs` using `layout` and having `title`."""
    slide = prs.slides.add_slide(layout)
    slide.shapes.title.text = title
    slide.placeholders[1].text = data1
    slide.placeholders[2].text = data2
    return slide


var1 = "Secondary header for Slide1 !!!"

#Defination to create the new slide with layout and title:
title_slide_layout = prs.slide_layouts[3]
slide1 = add_slide(prs, title_slide_layout, "Summary Table", "This is the text for slide 1", var1)

This works properly when i do not use a templete but when i do, it gives an error:

Traceback (most recent call last):
  File "C:/Users/test.py", line 47, in <module>
    slide1 = add_slide(prs, title_slide_layout, "Summary Table", "This is the text for slide 1", var1)
  File "C:/Users/test.py", line 35, in add_slide
    slide.placeholders[1].text = data1
  File "C:\Users\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pptx\shapes\shapetree.py", line 730, in __getitem__
    raise KeyError("no placeholder on this slide with idx == %d" % idx)
KeyError: 'no placeholder on this slide with idx == 1'

Any help on the error is appreciated.


回答1:


This error means you've asked for a placeholder that does not exist on that slide.

Placeholder access is a little tricky, in that a placeholder is identified by its "key", not by its position in the (z-order) sequence of placeholders on the slide. This key is called "idx" (name chosen by Microsoft), which perhaps makes it more potentially confusing.

I recommend you read this page of the documentation to familiarize yourself with the details: https://python-pptx.readthedocs.io/en/latest/user/placeholders-using.html

The following code is an example of how you can query a slide for the keys (idxs) and names of the placeholders it contains, which will give you a valid set of choices:

>>> prs = Presentation()
>>> slide = prs.slides.add_slide(prs.slide_layouts[8])
>>> for shape in slide.placeholders:
...     print('%d %s' % (shape.placeholder_format.idx, shape.name))
...
0  Title 1
1  Picture Placeholder 2
2  Text Placeholder 3


来源:https://stackoverflow.com/questions/59561983/python-pptx-keyerror-no-placeholder-on-this-slide-with-idx-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!