Displaying Image In Tkinter Python

Introduction 

When it comes to Graphical User Interface based application, image(s) play a vital role. From the application icon to animation, it's useful.

To display images in labels, buttons, canvases, and text widgets, the PhotoImage class is used, which is present in tkinter package.

Display image using PhotoImage class

Example Code

from tkinter import *      
root = Tk()      
canvas = Canvas(root, width = 300, height = 300)      
canvas.pack()      
img = PhotoImage(file="ball.ppm")      
canvas.create_image(20,20, anchor=NW, image=img)      
mainloop() 

"PhotoImage()" function returns the image object.

Output

Display image using PhotoImage class

Display image using ImageTk and Image classes from PIL

To display image in Python is as simple as that. But, the problem is PhotoImage class only supports GIF and PGM/PPM formats.

The more generalized formats are JPEG/JPG and PNG. To open and display with those formats, we need help of ImageTk and Image classes from PIL(photo imaging Library) package.

With the help of PIL(photo imaging Library), we can load images in over 30 formats and convert them to image objects, even base64-encoded GIF files from strings!!

Example Code ??????

from tkinter import *  
from PIL import ImageTk,Image  
root = Tk()  
canvas = Canvas(root, width = 300, height = 300)  
canvas.pack()  
img = ImageTk.PhotoImage(Image.open("ball.png"))  
canvas.create_image(20, 20, anchor=NW, image=img) 
root.mainloop() 

Image class has an attribute "open()" which would open the not-so-directly-supported image formats and along with "ImageTk.PhotoImage()", we can return the image object and use it.

Output

Display image using ImageTk and Image classes from PIL

Note

If you display an image inside a function, then make sure to keep the reference to the image object in your Python program, either by storing it in a global variable or by attaching it to another object.

global img       
def foo(self):    
    img = ImageTk.PhotoImage(Image.open("ball.png"))     
def foo(self):      
    self.img = ImageTk.PhotoImage(Image.open("ball.png"))     
    self.canvas.create_image(20,20, anchor=NW, image=self.img)    
    self.canvas.image = self.img  

It's important because when you return from the function and if the image object is stored in a variable local to that function, the image is cleared by the garbage collector even if it's displayed by tkinter.