2017-10-17 230 views
2

由于我发布了这个问题,我已经在手头的问题上取得了轻微进展,我发现有必要将它分为两​​部分以保持清晰。如何使用Python和win32com.client在PowerPoint中操纵形状(颜色)?


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

1.使用Python

操纵形状颜色在PowerPoint中有关于如何使用PPTX库here编辑PowerPoint幻灯片的一些例子。但是,我发现使用win32com.client来操作活动PowerPoint演示文稿要简单得多,如here所述。使用从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=0x1更改为Orientation=0x5以更改shape1 = slide.Shapes.AddTextbox(Orientation=0x1,Left=100,Top=100,Width=100,Height=100)中的文本框的方向。

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

这不起作用:

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

错误消息:

enter image description here

我有很高的期望通过导入下面的一些信息RGB的功能来修复这个pypi.python.org

但我在pip install colour也遇到了麻烦:

enter image description here

现在我有点失去了所有的帐户,所以要操纵颜色的任何方式任何线索将是巨大的!

2.使用dir()

在我试图管理这些讨厌的颜色,检查在Python对象,我开始从dir(shape1.TextFrame)dir(shape1.TextFrame.Textrange)等检查输出。 令我失望的是,我找不到任何有关颜色的东西,甚至没有找到Font,虽然Font很容易操作。

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

谢谢你的任何建议!

回答

1

你可以在你的Python脚本

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

关于你的第二个问题很容易重新创建全球VBA函数。了解这些对象的最佳位置是Excel宏对象浏览器。在宏编辑器中时,按F2然后筛选Powerpoint库。然后,你可以搜索和探索相关到PowerPoint

Object Browser

+0

谢谢对象模型!这似乎工作正常,除了它看起来颜色有点乱了。 (255,0,0)是红色,(0,255,0)是绿色,(0,0,255)应该是蓝色,但是变成绿色。任何想法为什么? – vestland

+1

我的错误,请检查更新的函数 –

+0

关于第二个问题,是否真的没有办法在Python中定位这些对象/方法? – vestland