* EDIT * No I am not trying to convert a .BMP Just simply load a PNG and render it in a tk Canvas (with the transparent bits actually transparent.)
Goal: What to load PNG files with transparency and render them in tkinter Canvas with Python3 (and using Pillow for PIL support)
Problem: When loaded as RGBA, they fail to render in canvas. Converting them to RGB and they will render, but of course have no transparency.
Environment: Mac OSX, Python 3.5 installed and verified Pillow is in the 3.5 path
Notes: The CuriosityRover.png is indeed an RGBA, the print statement confirms, and verified with finder showing the grey background and Photoshop saving web with transparency.
I have tried extracting out just the alpha layer like this:
alpha = img.convert('RGBA').split()[-1]
Calling alpha.show() does indeed show me in Preview the alpha layer, but it fails to render in the canvas widget.
I also tried inverting the alpha layer using ImageOps.invert(alpha) (Verified via calling .show() after applying the invert and I see the reverse alpha layer in Preview.)
I have tried creating rectangular transparent areas like this: transparent_area = (0, 0, 300, 300) mask = Image.new('L', curosity.size, color=255) draw = ImageDraw.Draw(mask) draw.rectangle(transparent_area, fill=0) img.putalpha(mask)
And that does work in creating a transparent rectangular region, so it seems like the canvas.create_image is working fine with transparency, but somehow I am failing to create a PhotoImage with the transparency data correct.
I have so many stack overflow tabs open through the course of the day I am embarrassed that I cannot figure this out.
This seems like the simplest thing in the world. What am I doing wrong?
import tkinter as tk
from PIL import Image, ImageTk
img = Image.open("./Assets/CuriosityRover.png")
img2 = Image.open("./Assets/CuriosityRover.png").convert('RGB')
img.show() # Shows the image just fine in preview
print(img.format, img.size, img.mode)
root = tk.Tk()
photo = ImageTk.PhotoImage(img) # img fails render, img2 works but no alpha
canvas = tk.Canvas(root, width=600, height=600, bg="black")
canvas.create_image((300, 300), image=photo)
canvas.grid(row=0, column=0)
root.mainloop()