本文介绍了如何在for循环python-pptx中的同一张幻灯片中添加两个或更多图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python pptx包将图像添加到一张幻灯片中.

I'm trying to add images into one slide using python pptx package.

如何将两个图像添加到一个在python pptx中滑动

但是我在for循环中执行此操作时遇到了困难;

But I have difficulties with when I do this in a for loop;

假设我们在目录中有一堆图片,并且我们希望在调整目录中图片的同时调整大小并添加当前幻灯片.当我在目录中有 eagle hawk 时,请调整大小&放置它们并将它们放到当前幻灯片中,然后移动下一张!

let's say we have a bunch of pictures in the directory and we want to resize and add the current slide as we go along with the pictures in directory. When I have eagle or hawk in the directory resize & position them and put them into current slide and move the next one!

我得到的是每张图片在不同的幻灯片中

What I am getting is that each picture in different slides;

这是我的代码;

from pptx import Presentation
from pptx.util import Inches
from pptx.util import Inches

img_path = 'r/D/test'

eagle_1.png, eagle_2.png .... eagle_5.png

hawk_1.png, hawk_2.png .... hawk_5.png


def ppt_generator(img_path):

    prs = Presentation()
    blank_slide_layout = prs.slide_layouts[6]
    #slide = prs.slides.add_slide(blank_slide_layout)

    for images in glob.glob(img_path + '/*.png'):


        if 'eagle' in str(images):
            slide = prs.slides.add_slide(content_slide_layout)   
            slide = slide.shapes.add_picture(images , left=Inches(0), top=Inches(0), width=Inches(3), height = Inches(3))

        if 'hawk' in str(images):
            slide = prs.slides.add_slide(content_slide_layout)   
            slide = slide.shapes.add_picture(images , left=Inches(2), top=Inches(2), width=Inches(3), height = Inches(3))

    prs.save('eagle_hawk.pptx') 

我想要拥有的是每个eagle_1和hawk_1应该在同一张幻灯片中,依此类推!

What I want to have is that for each eagle_1 and hawk_1 should be in the same slide and so on!

我该怎么做?

推荐答案

一种方法是在单独的函数中组合eagle/hawk图片对.也许像这样:

One approach would be to assemble eagle/hawk picture pairs in a separate function. Maybe something like:

def iter_image_pairs():
    eagles, hawks = [], []
    for image_path in glob.glob(img_path + '/*.png'):
        if "eagle" in image_path:
            eagles.append(image_path)
        elif "hawk" in image_path:
            hawks.append(image_path)
    for pair in zip(eagles, hawks):
        yield pair

然后您的幻灯片循环就可以变成:

Then your slide loop can just become:

for eagle, hawk in iter_image_pairs():
    slide = prs.slides.add_slide(content_slide_layout)   
    slide.shapes.add_picture(
        eagle, left=Inches(0), top=Inches(0), width=Inches(3), height=Inches(3)
    )
    slide.shapes.add_picture(
        hawk, left=Inches(2), top=Inches(2), width=Inches(3), height=Inches(3)
    )

这篇关于如何在for循环python-pptx中的同一张幻灯片中添加两个或更多图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 12:21