How to draw a png image on a Python tkinter canvas?

TkinterPythonGUI-Programming

To work with images in tkinter, Python provides PIL or Pillow toolkit. It has many built-in functions that can be used to operate an image of different formats.

To open an image in a canvas widget, we have use create_image(x, y, image, **options) constructor. When we pass the Image value to the constructor, it will display the image in the canvas.

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("700x600")

# Create a canvas widget
canvas=Canvas(win, width=700, height=600)
canvas.pack()

# Load the image
img=ImageTk.PhotoImage(file="Monalisa.png")

# Add the image in the canvas
canvas.create_image(350, 400, image=img, anchor="center")

win.mainloop()

Output

Running the above code will display a window that contains image in the canvas.

raja
Published on 05-Aug-2021 13:55:38
Advertisements