Search code examples
pythonpowerpointpython-pptx

Python PPTX library issue - Replacing image in slides ('SlidePart' object has no attribute 'related_parts')


I use the PPTX library to automate the creation of a deck of slides on a weekly basis. It was working really well until the last update of the library. As you can see below, I keep getting the following when updating the "image part" of the slides:


AttributeError: 'SlidePart' object has no attribute 'related_parts'


Here is my function for the image replacement:


def replace_img_slide(prs, slide_nbr, shape_nbr, img_path):

slide = prs.slides[slide_nbr]
img = slide.shapes[shape_nbr]
try:
    imgPic = img._pic
except AttributeError:
    raise AttributeError(
        f"Error for slide: {slide_nbr}, shape: {shape_nbr}, path: {img_path}")
imgRID = imgPic.xpath('./p:blipFill/a:blip/@r:embed')[0]
imgPart = slide.part.related_parts[imgRID]

with open(img_path, 'rb') as f:
    rImgBlob = f.read()

# replace
imgPart._blob = rImgBlob

return prs

I found some related subject and I understood that the "related_parts" is now obsolete in the new version of the library but I did not find how to solve it. Do you think you can help me with that please ?

Many thanks in advance for your help !


Solution

  • Just use part.related_part(imgRID) where you used to use part.related_parts[imgRID].

    The latest version exposes that method (internally) rather than expose a dict-like object just to do that one job.