16

I put in a partially transparent PNG image in Tkinter and all I get is this

alt text

How do I make the dark triangle on the right clear? (like it's supposed to be)

This is python 2.6 on Windows 7, btw.

rectangletangle
  • 50,393
  • 94
  • 205
  • 275

1 Answers1

25

Here's an example (the PNG file example.png has lots of transparency in different places):

from Tkinter import Tk, Frame, Canvas
import ImageTk

t = Tk()
t.title("Transparency")

frame = Frame(t)
frame.pack()

canvas = Canvas(frame, bg="black", width=500, height=500)
canvas.pack()

photoimage = ImageTk.PhotoImage(file="example.png")
canvas.create_image(150, 150, image=photoimage)

t.mainloop()

You need to make sure the image has been stored as "RGBA" which is RGB with an alpha channel. You can check for that using a graphics program of your choice, or using PIL (Python Imaging Library):

import Image
im = Image.open("button.png")
print im.mode

This should print "RGBA". If not, you'll have to make sure the alpha channel is saved with the image. You'll have to consult your graphics program manual for how to do that.

SamTheProgrammer
  • 1,051
  • 1
  • 10
  • 28
Fabian Fagerholm
  • 4,099
  • 1
  • 35
  • 45
  • 10
    It might me noteworthy that `ImageTk` is not part of the Python standard library, but of the Python Imaging Library, which has to be installed seperately. Also, PIL has not yet Python 3 support, so the above code will only work on Python 2.x. – fbmd Feb 12 '13 at 08:40
  • 1
    @fbmd: Good comments. Here's a related post: http://stackoverflow.com/questions/3896286/image-library-for-python-3 – Fabian Fagerholm Feb 14 '13 at 09:05
  • 6
    PIL has been forked by and more or less superseded by the pillow package, which *does* support 3.x. – Terry Jan Reedy Oct 19 '15 at 06:49