如何使用 Python 和 win32com.client 在 PowerPoint 中操作形状(颜色)?

How can I manipulate shapes (colors) in PowerPoint using Python and win32com.client?

自从我发布这个问题以来,我手头的问题已经取得了一些进展,我发现有必要将它分成两部分以保持清晰。


  1. 如何使用 Python 和 win32com.client 在 PowerPoint 中处理形状颜色?
  2. 如何使用 dir() 检查 Python 中的 com 对象?

1。使用 Python

在 PowerPoint 中处理形状颜色

有一些关于如何使用 pptx 库编辑 PowerPoint 幻灯片的示例 here. However, I find it much easier to manipulate an active PowerPoint presentation using win32com.client as described here. Using an example from Microsoft Developer Network 我发现我可以轻松复制 部分 此 VBA 片段的功能...

With ActivePresentation.Slides(1).Shapes(1)
    With .TextFrame.TextRange.Font
        .Size = 48
        .Name = "Palatino"
        .Bold = True
        .Color.RGB = RGB(255, 127, 255)
    End With
End With

...使用此 Python 片段:

import win32com.client
Application = win32com.client.Dispatch("PowerPoint.Application") 
Presentation = Application.Activepresentation

slidenr = Presentation.Slides.Count    
slide = Presentation.slides(slidenr)
    
shape1 = slide.Shapes.AddTextbox(Orientation=0x1,Left=100,Top=100,Width=100,Height=100)
shape1.TextFrame.TextRange.Text='Hello, world'    

#Manipulate font size, name and boldness
shape1.TextFrame.TextRange.Font.Size=20
shape1.TextFrame.TextRange.Characters(1, 4).Font.Name = "Times New Roman"
shape1.TextFrame.TextRange.Font.Bold=True

在这里我可以操纵字体大小和名称。我还可以通过更改来更改文本框的方向 Orientation=0x1Orientation=0x5shape1 = slide.Shapes.AddTextbox(Orientation=0x1,Left=100,Top=100,Width=100,Height=100).

编辑框或字体颜色似乎不可能。

这不起作用:

shape1.TextFrame.TextRange.Font.Color.RGB = RGB(255, 127, 255)

错误信息:

我非常希望通过在 pypi.python.org

上的信息导入一些 RGB 功能来解决这个问题

但我也遇到了 pip install colour:

的问题

到现在为止,我对所有帐户都有点迷失了,所以任何关于操纵颜色的任何方式的提示都会很棒!

2。使用 dir()

检查 Python 中的对象

在尝试管理那些讨厌的颜色时,我开始检查 dir(shape1.TextFrame)dir(shape1.TextFrame.Textrange) 等的输出。 令我失望的是,我找不到任何关于颜色的信息,甚至找不到字体,尽管字体显然可以进行操作。

所以我的第二个问题是:这根本不是检查和操作这些形状的方法吗?我怎样才能找到正确的对象(或方法?)来进一步操纵 shape1?我看过 PowerPoint objectmodel,但收效甚微。

感谢您的任何建议!

您可以在 python 脚本中轻松地重新创建全局 VBA 函数

def RGB(red, green, blue):
    assert 0 <= red <=255    
    assert 0 <= green <=255
    assert 0 <= blue <=255
    return red + (green << 8) + (blue << 16)

关于你的第二个问题。了解这些对象的最佳位置是 Excel 宏对象浏览器。在宏编辑器中时,按 F2,然后筛选 Powerpoint 库。然后你可以搜索和探索与powerpoint

刚相关的对象模型