Basics For Displaying Image In Tkinter Python

When it comes to Graphical User Interface based application, image(s) play a vital role. From 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.
 
Example Code 
  1. from tkinter import *      
  2. root = Tk()      
  3. canvas = Canvas(root, width = 300, height = 300)      
  4. canvas.pack()      
  5. img = PhotoImage(file="ball.ppm")      
  6. canvas.create_image(20,20, anchor=NW, image=img)      
  7. mainloop()   
"PhotoImage()" function returns the image object.
 
Output
 
 
 
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
  1. from tkinter import *  
  2. from PIL import ImageTk,Image  
  3. root = Tk()  
  4. canvas = Canvas(root, width = 300, height = 300)  
  5. canvas.pack()  
  6. img = ImageTk.PhotoImage(Image.open("ball.png"))  
  7. canvas.create_image(20, 20, anchor=NW, image=img) 
  8. 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
 
 
 
Note
 
If you display an image inside a function, then make sure to keep reference to the image object in your Python program, either by storing it in a global variable or by attaching it to another object.
  1. global img       
  2. def foo(self):    
  3.     img = ImageTk.PhotoImage(Image.open("ball.png"))     
  1. def foo(self):      
  2.     self.img = ImageTk.PhotoImage(Image.open("ball.png"))     
  3.     self.canvas.create_image(20,20, anchor=NW, image=self.img)    
  4.     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.
Ebook Download
View all
Learn
View all