How to draw images in the Tkinter window?

TkinterServer Side ProgrammingProgramming

To process images with Tkinter and other Python packages, we generally refer to use Pillow Package or PIL in Python. It provides a way to load and process the images in the program wherever we need. Initially, we convert the image to an instance of PhotoImage object that allows images to be further used in many use cases. Further, the Canvas widget in Tkinter helps to draw the images in a Tkinter application, we can use the create_image(x,y, image_file) method to display the image in a particular application.

Example

#Import the required Libraries
from tkinter import *
from PIL import Image,ImageTk
#Create an instance of tkinter frame
win = Tk()
#Set the geometry of tkinter frame
win.geometry("750x270")
#Create a canvas
canvas= Canvas(win, width= 600, height= 400)
canvas.pack()
#Load an image in the script
img= ImageTk.PhotoImage(Image.open("download.png"))
#Add image to the Canvas Items
canvas.create_image(10,10,anchor=NW,image=img)
win.mainloop()

Output

Running the above code will display a window that will display an image in the Canvas Widget.

In order to replace or change the Image file in the given output just import the image in Image.Open(file name) method.

raja
Published on 03-May-2021 11:03:46
Advertisements