python-pptx 在 PlaceholderPicture 中插入图片

huangapple go评论107阅读模式
英文:

python-pptx insert picture in PlaceholderPicture

问题

我正在尝试在pptx占位符中插入图片

for shape in presentation.slides[(len(presentation.slides) - 1)].placeholders:
    print(shape.name)
    print(shape.shape_type)
    print(shape.placeholder_format.type)

    if "Bild" in shape.name:
        shape.insert_picture(os.path.join(self.image_folder, "media_value.png"))

我的输出:

Bildplatzhalter 17
PLACEHOLDER (14)
PICTURE (18)

错误信息:

shape.insert_picture(os.path.join(self.image_folder, "media_value.png"))
AttributeError: 'PlaceholderPicture' object has no attribute 'insert_picture'

文档中看,应该像这样工作。我做错了什么?

英文:

I'm trying to insert a picture in a pptx Placeholder

for shape in presentation.slides[(len(presentation.slides) - 1)].placeholders:
    print(shape.name)
    print(shape.shape_type)
    print(shape.placeholder_format.type)
    
    if "Bild" in shape.name:
        shape.insert_picture(os.path.join(self.image_folder, "media_value.png"))

my output:

Bildplatzhalter 17
PLACEHOLDER (14)
PICTURE (18)

the error:

shape.insert_picture(os.path.join(self.image_folder, "media_value.png"))
AttributeError: 'PlaceholderPicture' object has no attribute 'insert_picture'

From the Documentation, it should work like this.
what i'm doing wrong?

python3.9
python-pptx0.6.21

答案1

得分: 1

你需要将这段代码翻译成中文吗?如果是的话,以下是翻译好的部分:

# 创建一个新的演示文稿对象
presentation = Presentation()

# 指定幻灯片布局。幻灯片布局 8 具有图片占位符
slide_layout = presentation.slide_layouts[8]

# 向演示文稿添加具有指定布局的幻灯片
slide = presentation.slides.add_slide(slide_layout)

# 指定占位符。占位符 1 是图片占位符。
# 选择其他占位符将导致错误
placeholder = slide.placeholders[1]

# 指定图像文件的路径
img_path = "Animal 1.jpg"

# 将图像插入占位符
placeholder = placeholder.insert_picture(img_path)

# 保存演示文稿
presentation.save('image.pptx')

这是代码的翻译部分。如果您需要更多帮助或有其他问题,请随时提出。

英文:

The placeholder you are inserting into needs to be a picture placeholder rather than a text one.

from pptx import Presentation
from pptx.util import Inches

# Create a new presentation object
presentation = Presentation()

# Specify the slide layout. Slide layouts 8 has a picture placeholder
slide_layout = presentation.slide_layouts[8]

# Add a slide with the specified layout to the presentation
slide = presentation.slides.add_slide(slide_layout)

# Specify the placeholder. Placeholder 1 is the picture placeholder.
# Choosing another placeholder will return an error
placeholder = slide.placeholders[1]

# Specify the path to the image file
img_path = "Animal 1.jpg"

# Add the image to the placeholder
placeholder = placeholder.insert_picture(img_path)

# Save the presentation
presentation.save('image.pptx')

huangapple
  • 本文由 发表于 2023年7月6日 22:42:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76630012.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定