2017-10-17 254 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