Image Wrap in Pillow

67 Views Asked by At

Is there a way to get an image to not block another image behind it?

I have attached 2 images of the code with one image loaded, and one with both.

I've been encounter a specific issue when loading multiple images into a customtkinter app. This issue I feel is quite simple, but has been driving me crazy. I can load an image just fine, but when you introduce another image, it seems it accounts for the entire image. EVEN THOUGH the image is transparent, it still manages to block the images behind it.

import customtkinter as ctk
from PIL import Image, ImageTk

app = ctk.CTk()
app.configure(bg="#222")
app.geometry("600x600")

grid = Image.open("grid.png")
grid_image = ImageTk.PhotoImage(grid)
grid_label = ctk.CTkLabel(app, image=grid_image, text='')
grid_label.place(x=25, y=25)

line = Image.open("line.png").rotate(45, expand=1)
line_image = ImageTk.PhotoImage(line)
line_label = ctk.CTkLabel(app, image=line_image, text='')
line_label.place(x=10, y=10)

app.mainloop()

The problem only arises when an image is placed on an existing image. This is the best I could simplify this issue to.

1 image Both images

I have tried .convert('RGBA') and .rotate(45, fillcolor=tuple(np.mean(np.array(line_i)[0,:], axis=0).astype(int))) I have also tried using ImageChops.

Has anyone else solved this issue?

1

There are 1 best solutions below

0
DonH On

You can't accomplish this by overlaying two PhotoImages in tkinter - I suggest you look at pillow's pil.Image.blend function and create a new composite image using your two souce images. You can use the alpha parameter to Image.blend to adjust the transparency of the images.

Here's the basic sequence.

  • Start with your two images opened as pil.Image objects
  • Then use Image.blend to create a new blended image object
  • Convert that new object to an ImageTk.PhotoImage for display in Tkinter

Looking at your attached images, it looks like you want to overlay the line image on the grid one.

If instead, you want the composited image to be bigger than either image and have the images partly overalp, the it would probably be easiest to create a image in the background color that contains the entire figure then blend both images onto that one.

Hope this helps with your problem.