在 python-pptx 中阅读 powerpoint 主题颜色

Read in powerpoint theme colours in python-pptx

有没有办法通过 python-pptx 从给定的 powerpoint 读取主题颜色,也就是强调颜色?

我希望有人有一个未记录的方法来执行此操作,因为现在库中不存在此功能。

为此,您需要访问主题部分,获取其 XML,然后对其进行解析或使用某种正则表达式搜索来查找所需的值。

您正在寻找的 XML 看起来像这样:

<a:theme
    xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
    name="Office Theme">
  <a:themeElements>
    <a:clrScheme name="Office">
      <a:dk1><a:srgbClr val="444444"/></a:dk1>
      <a:lt1><a:srgbClr val="FFFFFF"/></a:lt1>
      <a:dk2><a:srgbClr val="888888"/></a:dk2>
      <a:lt2><a:srgbClr val="DFDFDF"/></a:lt2>
      <a:accent1><a:srgbClr val="306396"/></a:accent1>
      <a:accent2><a:srgbClr val="D03E3E"/></a:accent2>
      <a:accent3><a:srgbClr val="FDB72A"/></a:accent3>
      <a:accent4><a:srgbClr val="37AD6C"/></a:accent4>
      <a:accent5><a:srgbClr val="8A479B"/></a:accent5>
      <a:accent6><a:srgbClr val="1CBECF"/></a:accent6>
      <a:hlink><a:srgbClr val="0563C1"/></a:hlink>
      <a:folHlink><a:srgbClr val="954F72"/></a:folHlink>
    </a:clrScheme>

您可以使用它访问您想要的部分(可能需要一些调整):

from pptx.opc.constants import RELATIONSHIP_TYPE as RT
from pptx.oxml import parse_xml
from pptx.oxml.ns import qn  # ---makes qualified name---

# ---access the theme part---
prs = Presentation("presentation-with-theme-I-want-colors-from.pptx")
presentation_part = prs.part
theme_part = presentation_part.part_related_by(RT.THEME)

# ---access theme XML from part---
theme_xml = theme_part.blob
print(theme_xml) # ---should look like example above, just longer---

# ---parse XML---
theme_element = parse_xml(theme_xml)

# ---find color elements---
color_elements = theme_element.xpath(".//%s/child::*" % qn("a:clrScheme"))
print(len(color_elements)  # ---should be 12, of which you care about 6---
for e in color_elements:
    print(e.tag)
    print(e[0].get("val"))

这里后面的部分使用了lxml.etree._Element接口,需要的话可以上网学习做不同的操作
https://lxml.de/api/lxml.etree._Element-class.html