如何在 python pptx 中为形状添加透明度?

How do I add transparency to shape in python pptx?

def new_presentation():
    prs=Presentation()
    img="C:/Users/Dennis/Desktop/Tom-Hiddleston-4-1024x768.jpg"
    mainsld=new_slide(prs, 6)
    mainshp=mainsld.shapes
    mainshp.add_picture(img, 0,0, Inches(10))
    titleshape=mainshp.add_shape(MSO_SHAPE.RECTANGLE, Inches(0), Inches(1), Inches(10), Inches(1))
    titleshape.fill.solid()
    titleshape.fill.fore_color.rgb=RGBColor(0x00,0x64,0x00)
    titleshape.fill.transparency = 0.25 ##doesnt work???##########################
    titleshape.line.fill.background()
    titlebox=mainshp.add_textbox(Inches(1), Inches(0.8),Inches(1), Inches(1)).text_frame.add_paragraph()
    titlebox.text="TOM HIDDLESTON"
    titlebox.font.name="Calibri"
    titlebox.font.size=Pt(36)
    titlebox.font.color.rgb=RGBColor(0x90,0x90,0x00)
    prs.save('test.pptx')

标有“######s”的行应该使形状更透明,如 pptx 文档中所写 - 它是 shape.fill 属性 。代码中的其他一切都完美无缺。我正在使用 python 2.7 和最新的 pptx。预先感谢您的帮助。

FillFormat.transparency 尚未实施。您看到的文档部分可能是一个分析页面,它是开发的前身。

这是分析页面: http://python-pptx.readthedocs.io/en/latest/dev/analysis/features/dml-fill.html?highlight=transparency

这是开发的 FillFormat (.fill) API: http://python-pptx.readthedocs.io/en/latest/api/dml.html#fillformat-objects

但是,您可以使用 FillFormat 对象中的 lxml 调用来操作其下的 XML。您可能希望从 .fill 元素中的 spPr 元素开始:

spPr = titleshape.fill._xPr
print spPr.xml

下面是执行此类操作的一个示例: https://groups.google.com/forum/#!msg/python-pptx/UTkdemIZICw/qeUJEyKEAQAJ

如果您搜索术语 python-pptxOxmlElementlxmlworkaround function 的各种组合,您会找到更多信息。

经过大量挖掘,我已经能够为此提出解决方案

from pptx import Presentation
from pptx.oxml.xmlchemy import OxmlElement
from pptx.util import Cm
from pptx.enum.shapes import MSO_SHAPE
from pptx.dml.color import RGBColor

def SubElement(parent, tagname, **kwargs):
        element = OxmlElement(tagname)
        element.attrib.update(kwargs)
        parent.append(element)
        return element

def _set_shape_transparency(shape, alpha):
    """ Set the transparency (alpha) of a shape"""
    ts = shape.fill._xPr.solidFill
    sF = ts.get_or_change_to_srgbClr()
    sE = SubElement(sF, 'a:alpha', val=str(alpha))

## Create presentation
prs = Presentation()
## Add a slide (empty slide layout)
slide = prs.slides.add_slide(prs.slide_layouts[6])
##Add a blue box to the slide
blueBox = slide.shapes.add_shape(autoshape_type_id=MSO_SHAPE.RECTANGLE,
                         left=Cm(0),
                         top=Cm(0),
                         height=Cm(10),
                         width=Cm(20))
## Make the box blue
blueBoxFill = blueBox.fill
blueBoxFill.solid()
blueBoxFillColour = blueBoxFill.fore_color
blueBoxFillColour.rgb = RGBColor(0,176,240)
## Set the transparency of the blue box to 56%
_set_shape_transparency(blueBox,44000)
## Save the presentation
prs.save(your_path)