python-pptx中的图片插入失败,并出现以下错误:LayoutPlaceholder没有属性insert_picture

时间:2019-05-02 14:56:54

标签: python python-pptx

尽管我可以生成演示文稿,填充文本占位符而不会出现问题并成功保存生成的演示文稿,但是在尝试填充图片占位符时,我始终遇到错误。我已经确认我正在使用正确的占位符对象,并且它是图片占位符(类型18)。我已经编写了代码,以遵循在线文档中的示例,并且目前还无法弄清为什么出现此错误:

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

这是正在执行的代码部分,在执行最后一行后抛出错误:

# Bring in a new slide from layout and add to deck
objContentSlide = objPrs.slide_layouts[1]
objPrs.slides.add_slide(objContentSlide)

# Collect the placeholders
objContentShapes = objContentSlide.placeholders

# Populate title placeholder (text)
objContentSlideTitle = list(filter(lambda x: x.name == "slide1Title",objContentShapes))[0]
objContentSlideTitle.text = CNSDETAILSLIDETITLEPREFIX + strMonthName + CNSDETAILSLIDETITLESUFFIX

# Populate forecast placeholder (text)
objContentSlideForecast = list(filter(lambda x: x.name == "slide1Forecast",objContentShapes))[0]
objContentSlideForecast.text = CNSDETAILSLIDEFORECASTPREFIX + strRandomNumber0

# Populate assumptions placeholder (text)
objContentSlideAssumptions = list(filter(lambda x: x.name == "slide1Assumptions",objContentShapes))[0]
objContentSlideAssumptions.text = CNSDETAILSLIDEASSUMPTIONSPREFIX + CNSDETAILSLIDEASSUMPTIONSSTAGE + CNSDETAILSLIDEASSUMPTIONSSUFFIX + strRandomNumber1

# Populate screenshot
objContentSlideScreenshot = list(filter(lambda x: x.name == "slide1Screenshot",objContentShapes))[0]
plcName = objContentSlideScreenshot.name # Returns "slide1Screenshot"
plcType = objContentSlideScreenshot.placeholder_format.type # Returns 18
objContentSlideScreenshot.insert_picture("testShot.png",0,0)

我通常不使用Python(但是很喜欢),所以请让我知道是否存在我不知道的明显的约定问题。

1 个答案:

答案 0 :(得分:2)

该库的文档建议使用referencing the placeholder by it's idx

  

访问已知占位符的最可靠方法是通过其 idx

因此,我将考虑实施该方法。而且,也许更重要的是,在这里,您正在使用SlideLayout,而不是幻灯片实例!布局包含形状和占位符,但它们与幻灯片实例上的形状和占位符不同。 (PPT的对象模型每天都会找到使您困惑的新方法。)

objContentSlide = objPrs.slide_layouts[1]
objPrs.slides.add_slide(objContentSlide)

#collect the placeholders
objContentShapes = objContentSlide.placeholders

在其余代码中,objContentSlide指的是SlideLayout,而不是Slide实例,并解释了为什么您似乎在处理LayoutPlaceholder而不是a Placeholder

相反,我将执行以下操作(未经测试):

layout = objPrs.slide_layouts[1]  # handle the desired layout
slide = objPrs.slides.add_slide(layout) # create a slide instance from the layout
slide_shapes = slide.shapes
placeholders = slide.placeholders # handles the placeholders on our new slide instance

...

screenshot = list(filter(lambda x: x.name == "slide1Screenshot", slide_shapes))[0]
idx = screenshot.placeholder_format.idx
screenshot = placeholders[idx]
screenshot.insert_picture("testShot.png",0,0)