2

Use-case: I make a presentation in python-pptx and then manually go in and add some slide and then remember that I need to change one or more of the pictures. Then I want to be able to run the program again and have it replace the picture with the same name.

My problem is that sometimes it works, usually the first time, and the picture is replaced with the same descr but more often then not, it is replaced with image.png and because of this i am unable to find that picture the next time I try to replace. Does any one has any ideas? Here is my replace function:

   def replace(self, newPic):
    for slide in self.pres.slides:
        for shape in slide.shapes:
            try:
                if shape._pic.nvPicPr.cNvPr.get('descr') == newPic:
                    top, left, width, height = shape.top, shape.left, shape.width, shape.height
                    self.deleteShape(shape)
                    img = slide.shapes.add_picture(self.inDir + "/" + newPic, left, top, width, height)
                    imgDescr = img._pic.nvPicPr.cNvPr.get('descr')
                   
            except AttributeError:
                pass

I also tried the following,

def replace(self, newPic):
    #If in list with every figure
    for slide in self.pres.slides:
        for shape in slide.shapes:
            try:
                if shape._pic.nvPicPr.cNvPr.get('descr') == newPic:
                    imgPic = shape._pic
                    imgRID = imgPic.xpath('./p:blipFill/a:blip/@r:embed')[0]
                    imgPart = shape.part.relatedpart(imgRID)

                    with open(self.inDir + "/" + newPic, 'rb') as f:
                        rImgBlob = f.read()

                    # replace
                    imgPart._blob = rImgBlob
            except AttributeError:
                pass

However here i got an attribute error

imgPart = shape.part.relatedpart(imgRID) AttributeError: 'SlidePart' object has no attribute 'relatedpart'

Selfors
  • 41
  • 3
  • I have now narrowed the problem down a little, it only changes the description of the image if it is an already used image. Maybe it has something to do with the delete function? def deleteShape(self, shape): shape._element.getparent().remove(shape._element) – Selfors Jun 15 '22 at 06:12
  • You have my interest: What does descr actually do? I ask because my code (md2pptx) uses python-pptx to add pictures. I have other ways of annotating them but didn't know about descr. It might be useful to my efforts. Thanks. – Martin Packer Jun 15 '22 at 07:23
  • 1
    descr returns the filename of the pictureShape i want to replace. So basically I am comparing if a picture has the same name as the one i want to incert and if it does I want to replace it. However, if the image is identical to an already existing one the replaced image get descr image.png instead of the name. – Selfors Jun 15 '22 at 07:29

0 Answers0