【问题标题】:How can I manipulate shapes (colors) in PowerPoint using Python and win32com.client?如何使用 Python 和 win32com.client 在 PowerPoint 中操作形状(颜色)?
【发布时间】:2017-10-17 12:18:24
【问题描述】:

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


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

1。使用 Python 在 PowerPoint 中处理形状颜色

有一些关于如何使用 pptx 库 here 编辑 PowerPoint 幻灯片的示例。但是,我发现使用 win32com.client 操作活动的 PowerPoint 演示文稿要容易得多,如 here 所述。使用来自Microsoft Developer Network 的示例,我发现我可以轻松复制此 VBA sn-p 的功能的部分...

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 sn-p:

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

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

不过,编辑框或字体颜色似乎是不可能的。

这不起作用:

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 powerpoint win32com


    【解决方案1】:

    您可以在 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相关的对象模型了

    【讨论】:

    • 谢谢!这似乎工作正常,除了它看起来颜色有点乱。 (255,0,0) 是红色,(0,255,0) 是绿色,(0,0,255) 应该是蓝色,但结果是绿色。有什么想法吗?
    • 关于第二个问题,真的没有办法在Python中定位这些对象/方法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    相关资源
    最近更新 更多