In this TKinter tutorial we are going to learn how to Add Image in TKinter Canvas, as you know the Canvas is a rectangular area intended for drawing pictures or other complex layouts. You can place graphics, text,widgets or frames on a Canvas. We Can Create Difference like arc, polygon, image, line. and we have already learned that how you can create arc in the canvas, now we want to add an image in the canvas.
For this lesson you need to install Pillow library, so Pillow is the friendly PIL fork by Alex Clark and Contributors. PIL is the Python Imaging Library by Fredrik Lundh and Contributors.
1 |
pip install Pillow |
This is the complete code for this lesson.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
from tkinter import * from PIL import ImageTk, Image class Window(Tk): def __init__(self): super(Window, self).__init__() self.title("Canvas In TKinter") self.minsize(500,400) self.wm_iconbitmap("myicon.ico") self.create_canvas() def create_canvas(self): canvas = Canvas(self, bg = "red", height = 250, width = 300) coord = 10,50, 240, 210 canvas.pack(expand = YES, fill=BOTH) img = Image.open("cake.jpg") canvas.image = ImageTk.PhotoImage(img) canvas.create_image(0,0, image = canvas.image, anchor = 'nw') window = Window() window.mainloop() |
So you can see at the top we have imported these two classes from PIL library.
1 |
from PIL import ImageTk, Image |
You can use tk.Canvas() for creating of the canvas, you need to give some parameters like background color, height and weight of the canvas.
1 |
canvas = Canvas(self, bg = "red", height = 250, width = 300) |
First we are going to open the image, make sure that you have already added an image in your working directory, after that we can use create_image() from the canvas for creating the image.
1 2 3 |
img = Image.open("cake.jpg") canvas.image = ImageTk.PhotoImage(img) canvas.create_image(0,0, image = canvas.image, anchor = 'nw') |
Run the complete code and this is the result.