How to use images in Tkinter using photoimage objects?

TkinterPythonGUI-Programming

Python supports PIL or Pillow package which is an open-source library for opening, manipulating, and saving different formats of images in Python projects. We can use it in our Tkinter application to process and display images.

The Label widget in Tkinter is used to render text and images in a Tkinter application. To display images with Label widget in a Tkinter application, we can follow these steps,

  • Make sure that Pillow or PIL package is installed in your system.

  • Load the image in a variable using ImageTk.PhotoImage(file=file_location) function.

  • Create a Label widget to assign the image value as the image.

  • Execute the code to display the image.

Example

# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x470")

# load the image and convert it into Tkinter Photoimage
bg=ImageTk.PhotoImage(file="baseball.png")

# Add a label widget to display the image
label=Label(win, image=bg)
label.place(x=0, y=0)

win.mainloop()

Output

Run the code to display images in a Tkinter window.

raja
Published on 19-Jun-2021 08:11:09
Advertisements