问题
I'm trying to add images into one slide using python pptx package.
How to add two images to one slide in python pptx
But I have difficulties with when I do this in a for loop;
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;
Here is my code look like;
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')
What I want to have is that for each eagle_1 and hawk_1 should be in the same slide and so on!
How can I do that?
回答1:
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)
)
来源:https://stackoverflow.com/questions/59977855/how-to-add-two-or-more-images-to-the-same-slide-in-for-loop-python-pptx