简体   繁体   English

更改python-pptx中部分文本的字体

[英]Changing font for part of text in python-pptx

I'm using the python-pptx module to create presentations.我正在使用 python-pptx 模块来创建演示文稿。 How can I change the font properties only for a part of the text?如何仅更改部分文本的字体属性?

I currently change the font like this:我目前改变字体是这样的:

# first create text for shape
ft = pres.slides[0].shapes[0].text_frame
ft.clear()
p = ft.paragraphs[0]
run = p.add_run()
run.text = "text"

# change font
from pptx.dml.color import RGBColor
from pptx.util import Pt

font = run.font
font.name = 'Lato'
font.size = Pt(32)
font.color.rgb = RGBColor(255, 255, 255)

Thanks!谢谢!

In PowerPoint, font properties are applied to a run .在 PowerPoint 中,字体属性应用于运行. In a way, it is what defines a run;在某种程度上,它定义了跑步; a "run" of text sharing the same font treatment, including typeface, size, color, bold/italic, etc.共享相同字体处理的文本“运行”,包括字体、大小、颜色、粗体/斜体等。

So to make two bits of text look differently, you need to make them separate runs.所以要让两个文本看起来不同,你需要让它们分开运行。

As @scanny says in another post.正如@scanny 在另一篇文章中所说。 The post 帖子

By "different run", it means you should write the text in first color in a run, then afterwards, write the text in the second color in another run as shown below. “不同的运行”意味着您应该在运行中以第一种颜色编写文本,然后在另一个运行中以第二种颜色编写文本,如下所示。

There's also an example in the post, I'll just copy and paste it to here帖子里还有一个例子,我就复制粘贴到这里

from docx.shared import RGBColor
# ---reuse existing default single paragraph in cell---

paragraph = cell.paragraphs[0]

###(First run)
#---add distinct runs of text one after the other to
# --- form paragraph contents.
paragraph.add_run("A sentence with a ")

###(Second run)
# ---colorize the run with "red" in it. 
red_run = paragraph.add_run("red")
red_run.font.color.rgb = RGBColor(255, 0, 0)


###(Third run)
paragraph.add_run(" word.")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM