Python-PPTX中的图片插入失败,错误:Layoutplaceholder没有属性insert_picture



尽管我可以生成演示文稿,填充文本占位符而无需问题,并成功保存了生成的演示文稿,但在试图填充图片占位符时,我一直在遇到错误。我已经确认我正在与正确的占位符对象合作,并且它是图片占位符(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工作(但完全喜欢(,所以请告诉我是否有一个明显的惯例问题。

此库的文档建议通过其idx引用占位符。

访问已知占位持有人的最可靠方法是通过其 idx value

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

objContentSlide = objPrs.slide_layouts[1]
objPrs.slides.add_slide(objContentSlide)
#collect the placeholders
objContentShapes = objContentSlide.placeholders

在您的其余代码中,objContentSlide指的是SlideLayout,而不是Slide实例,并解释了为什么您似乎正在处理LayoutPlaceholder而不是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)

相关内容

  • 没有找到相关文章