PIL ImageTk equivalent in Python 3.x
Asked Answered
B

3

9

I'm developing an application with Tkinter that uses a database of png image files for icons. In order to use said images in the application, I open them using PIL's Image.open, run it through the ImageTk.PhotoImage function, then pass it to the widget constructor.

The problem is, I'm trying to port my entire project over to Python 3.x, and because of PIL's lack of support for Python 3, I have no idea how to load the icons into the application.

If anyone knew of a solution that would allow me to use the icons without having to convert all of them to .gif bitmaps, I would be very grateful!

Blalock answered 17/6, 2012 at 4:13 Comment(0)
Q
10

PNG files, even with transparency, are correctly displayed in tkinter and ttk in python 3.4.1 on Linux, even though only GIF and PPM/PGM support is documented.

Example PNG File With Transparency And Alpha

Above PNG image contains transparency.

from tkinter import *          

root = Tk()                    

photo = PhotoImage(file="example.png")
photo_label = Label(image=photo)
photo_label.grid()             
photo_label.image = photo      

text = Label(text="Text") # included to show background color
text.grid()    

root.mainloop()

Above code renders the image correctly with transparency as seen below:

PNG Test Image In Python 3.4.1 tkinter with text

Please note that the screenshot was made on a setup without window decoration and with dark GUI color scheme.

Quartzite answered 3/8, 2014 at 6:13 Comment(0)
C
2

You can use Pillow to work with png images, in Python 3.3 or older versions.

Taken from here:

Pillow >= 2.0.0 supports Python versions: 2.6, 2.7, 3.2, 3.3. Pillow < 2.0.0 supports Python versions: 2.4, 2.5, 2.6, 2.7.

Ceasefire answered 4/7, 2013 at 20:24 Comment(0)
B
1

The example displays an image on the canvas.

from PIL import Image, ImageTk
# From the PIL (Python Imaging Library) module, we import the Image and ImageTk modules.


self.img = Image.open("tatras.jpg")
self.tatras = ImageTk.PhotoImage(self.img)


# Tkinter does not support JPG images internally. As a workaround, we
# use the Image and ImageTk modules.

canvas = Canvas(self, width=self.img.size[0]+20,  height=self.img.size[1]+20)

# We create the Canvas widget. It takes the size of the image into account. It is 20px wider and 20px higher than the actual image size.

canvas.create_image(10, 10, anchor=NW, image=self.tatras)
Barstow answered 14/10, 2019 at 3:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.