Skip to main content
 首页 » 编程设计

python之如何使用 python-pptx 更改形状内的字体颜色

2024年12月31日22yjmyzz

我正在尝试使用 Python 中的 python-pptx 模块创建一些形状。

我已经创建了形状,但是我无法编辑形状内文本的字体颜色。默认情况下,它以白色显示。我正在尝试查看如何更改文本颜色。以下是我到目前为止所构建的内容:

left = Inches(1.0) 
top = Inches(3.9) 
width = Inches(1.2) 
height = Inches(2.5) 
shape = shapes.add_shape( 
MSO_SHAPE.RECTANGLE, left, top, width, height 
) 
fill = shape.fill 
fill.solid() 
fill.fore_color.rgb = RGBColor(226, 206, 72)  # This RGB code is the background color that I want the shape to be in  
fill.fore_color.brightness = -0.3 
text_frame = shape.text_frame 
text_frame.clear() 
p = text_frame.paragraphs[0] 
run = p.add_run() 
run.text = 'Test message' 
font = run.font 
font.name = 'Arial' 
font.size = Pt(16) 
font.bold = True 

请您参考如下方法:

查看the documentation ,您应该能够通过在代码中添加一行(在底部)来完成此操作:

font.color.rgb = RGBColor(0x00, 0x00, 0x00)        # this would be black 

注意:记住,要使用 RGBColor,您必须导入它:

from pptx.dml.color import RGBColor