How do I insert a JPEG image into a Python Tkinter window?

TkinterPythonServer Side ProgrammingProgramming

Python provides the Pillow (PIL) package to support, process, and display the images in tkinter applications. A Tkinter application generally supports image files such as, ppm, png, and gif.

Let us suppose we want to embed and display a JPEG or JPG image in our application.

Tkinter Label widgets are generally used to display the text or images on the window and thus by passing the img value, we can display the JPEG image in the window.

Example

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

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

#Define the geometry of the window
win.geometry("650x400")

#Initialize the file name in a variable
path = "file.jpg"

#Create an object of tkinter ImageTk
img = ImageTk.PhotoImage(Image.open(path))

#Create a Label Widget to display the text or Image
label = tk.Label(win, image = img)
label.pack(fill = "both", expand = "yes")

win.mainloop()

Output

The code will display a JPEG image that is passed as the image value in the Label widget.

raja
Published on 27-Mar-2021 10:37:35
Advertisements