2

@scanny I have looked through python-pptx documentation and failed to find any method to delete a shape. The use case I am looking at is changing the shape present in the presentation based off secondary conditions. Is there any way to easily do this and or is there a way I could contribute to building this feature?

Appreciate the help.

Cole Spencer
  • 21
  • 1
  • 4

2 Answers2

4

Sadly,two line codes in scanny's answer cann't make it when i try to delete a shape.Maybe due to i don't know how to use lxml when 'pptx' is used(like share objects between lxml and'pptx' i think).But his answer inspire me to find the answer in manipulating xml. I'v looked for the answer for quite a while .Finally,I got the way to delete a shape! For example, i want yo delete the first shape of a shapes sequence,just use sub codes:

shapes.element.remove(shapes[0].element)  

and it works! thank @scanny,You've doing extraordinary job,it helps me a lot!

May0208
  • 41
  • 2
2

You can, and it works fine for simple shapes, but it is complicated by the fact that a shape can have relationships ("links" roughly) to other objects in the presentation and leaving those "dangling" can cause problems.

The basic idea is to delete the shape element using lxml calls, so something like this:

sp = shape._sp             # --- get reference to XML element for shape ---
sp.getparent().remove(sp)  # --- remove that shape element from its tree ---

This is the documentation for lxml.etree._Element, which each XML element in python-pptx subclasses (and thereby has all these methods). https://lxml.de/api/lxml.etree._Element-class.html

You'll know something went wrong if you get a "repair" error when trying to load the saved .pptx file. Simple shapes like rectangles and lines should be fine. Pictures, charts, and possibly shapes with hyperlinks may be problematic, but it's easy to try and you can see if it works in your case.

scanny
  • 26,423
  • 5
  • 54
  • 80
  • When I try to replace a shape with a different shape like this: width = shape1.width height = shape1.height .... sp = shape1._sp sp.getparent().remove(sp) new shape = groupshape1.shapes.add_shape(MSO_SHAPE.MATH_EQUAL,left,top,width,height) the positioning of the elements within the group shape above this is messed up: The hierarchy of group shapes is as such: GroupShape1 -----subGroupShapes ---------------shape1 – Cole Spencer Nov 05 '20 at 20:57
  • Sorry Cole, I can't make out the code in your comment. I took your question to be about deleting a shape and it looks like the method described in this answer works for that. If you accept this answer and ask another question (where you can format your code and focus on the group aspects) I'l take a look at it (make sure to include the `python-pptx` tag). – scanny Nov 06 '20 at 00:18