Search code examples
pythonpython-pptx

How to center a title in python .pptx?


Quick question: I'm working off a master document. The slide I am reference has the title aligned to the left. Simply put, how would you center the title?

Here's my current code

title = slide.shapes.title
title.text = 'Discussion'

I've looked a lot for this question, and all I could find were examples of centering text, but none on centering titles. Anyway, I hope this is a quick, easy, and helpful fix. Thanks!


Solution

  • A "title" is a shape. It's a little special in terms of how it's identified (always gets id=0 I believe), but otherwise no different than any other text-containing shape.

    A shape that can contain text (so not a picture, graphics-frame, line, or group) contains a text-frame that contains one or more paragraphs.

    Centered-alignment is an aspect of a paragraph. (Note that vertical alignment is an aspect of the text-frame.)

    So to do the needful here:

    from pptx.enum.text import PP_ALIGN
    
    title.text_frame.paragraphs[0].alignment = PP_ALIGN.CENTER
    

    If for whatever reason the title contains multiple paragraphs and you want all of them aligned center:

    for paragraph in title.text_frame.paragraphs:
        paragraph.alignment = PP_ALIGN.CENTER