Warm tip: This article is reproduced from stackoverflow.com, please click
python python-imaging-library tkinter

How to overlap two or more images using paste()?

发布于 2020-04-20 10:52:22

I'm working on a little GUI for a program written in Python that takes an amount to pay, an amount given and returns the change in form of images of notes and coins. Because of how tkinter works, I'm trying to optimize the space overlapping the images of the notes but I can't find a way to make the second images to not be cutted. This is the code I'm trying:

import tkinter as tk
from PIL import Image, ImageTk

window = tk.Tk()
window.title('main')
window.geometry('300x200')
test_image_1 = Image.open("fifty_pound.jpg")
test_image_1 = test_image_1.resize((250, 150), Image.ANTIALIAS)
test_image_2 = Image.open("twenty_pound.jpg")
test_image_2 = test_image_2.resize((250, 150), Image.ANTIALIAS)

Image.Image.paste(test_image_1, test_image_2, (50, 0))

test_image_1_render = ImageTk.PhotoImage(test_image_1)
test_image_label = tk.Label(image=test_image_1_render)
test_image_label.image = test_image_1_render
test_image_label.pack()

window.mainloop()

The result I'm getting is this:

Image returned

As you can see the 20 pound notes is cut. My questions are:

1) Is it possible to paste the 20 pound note picture overlapping the 50 pound ones without being cut?

2) How can I overlap more than two pictures in the same way?

Thanks a lot to everybody for the help.

Here the two images used: fifty_pound twenty_pound

Questioner
Py_Rog
Viewed
18
HansHirse 2020-02-05 19:45

I'm basically following the advice given to you in the comments – but since I was already preparing some code, that'd be my solution:

import tkinter as tk
from PIL import Image, ImageTk

# List of images (notes) to show
notes = ['fifty_pound.jpg', 'twenty_pound.jpg', 'twenty_pound.jpg']

# Same size for each note
x_note, y_note = (250, 150)

# Load images
notes = [Image.open(n).resize((x_note, y_note), Image.ANTIALIAS) for n in notes]

# Number of notes to show
n_notes = len(notes)

# Overlap (or offset) between notes
x_off, y_off = (50, 30)

# Calculate window size
window_size = (x_note + (n_notes - 1) * x_off, y_note + (n_notes - 1) * y_off)

# Create window
window = tk.Tk()
window.title('main')

# Create blank (white) image to paste notes on
new_image = Image.new('RGB', (window_size), (255, 255, 255))

# Paste notes
for i, n in enumerate(notes):
    Image.Image.paste(new_image, n, (i*x_off, i*y_off))

# Rendering
new_image_render = ImageTk.PhotoImage(new_image)
test_image_label = tk.Label(image=new_image_render)
test_image_label.image = new_image_render
test_image_label.pack()

window.mainloop()

Output:

Output

Hope that helps!

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
Pillow:      7.0.0
----------------------------------------