使用docx python库,如何同时应用颜色和字体大小

cph*_*sto 1 python fonts colors font-size python-docx

我正在使用 python docx 库写入 .docx 文件。我想预先指定特定句子的字体大小和颜色。我的问题是我无法同时进行。我来举例说明——

from docx import Document        
from docx.shared import Pt       #Helps to specify font size
from docx.shared import RGBColor #Helps to specify font Color
document=Document()              #Instantiation
p=document.add_heading(level=0)
p.add_run('I want this sentence colored red with fontsize=22').font.size=Pt(22)  #Specifies fontsize 22
p.add_run('This line gets colored red').font.color.rgb=RGBColor(255,0,0)    #Specifies RED color
document.save('path/file.docx')
Run Code Online (Sandbox Code Playgroud)

结果: 在此处输入图片说明

我很清楚地知道,我设置的颜色Red第二句,既然有一个=Pt(22)RGBColor(255,00)这样我就可以不适用fontsize,并color同时

有没有办法同时应用这两个属性?

编辑:我想要I want this sentence colored red with fontsize=22红色的线条。

小智 6

也许你可以做到这一点

document=Document()
p=document.add_heading(level=0)
wp = p.add_run('I want this sentence colored red with fontsize=22')
wp.font.size = Pt(22)
wp.font.color.rgb = RGBColor(255,0,0)
Run Code Online (Sandbox Code Playgroud)

  • 这正是我正在寻找的。非常干净的解决方案。非常感谢您,而且做得很好,因为今天是您使用 stackoverflow 的第一天。非常感谢! (2认同)