首页 > 解决方案 > 如何在 python-pptx 中更改幻灯片标题的字体?

问题描述

我想更改幻灯片标题的字体大小和字体样式。我还想在标题下划线。怎么做?

from pptx import Presentation

prs = Presentation(ppt_filename)

slide = prs.slides[0]
slide.shapes.title.text = 'New Title'
slide.shapes.title.top = 100
slide.shapes.title.left = 100
slide.shapes.title.height = 200

标签: pythonpython-pptx

解决方案


这可能有点hacky,但它有效。

根据文档,您可以访问标题占位text_frame形状
多亏了这一点,您可以Paragraph使用该属性在此框架内获取对象paragraphs。在此处的元素部分中,您可以看到title占位符形状位于第一个索引中(如果存在)。

然后我们现在可以获取Font段落中使用的内容,并更改它的不同属性,如下所示:

from pptx import Presentation
from pptx.util import Pt

prs = Presentation(ppt_filename)

slide = prs.slides[0]
slide.shapes.title.text = 'New Title'
slide.shapes.title.top = 100
slide.shapes.title.left = 100
slide.shapes.title.height = 200

title_para = slide.shapes.title.text_frame.paragraphs[0]

title_para.font.name = "Comic Sans MS"
title_para.font.size = Pt(72)
title_para.font.underline = True

额外参考:

  • text.Font- 更多可以编辑的字体属性。
  • util.Pt- 设置字体大小。

推荐阅读