How to center an image in canvas Python Tkinter


Let us consider that we are creating a GUI-based application using Tkinter and we want to load an image in the Tkinter canvas.

By default, the canvas loads the images according to its width and height. However, we can manipulate the position of an image in any direction (N,S,E,W,NS, EW, etc.) by passing the ‘Direction’ value in the anchor parameter. An anchor is a parameter which is invoked along with the image function; it defines the direction or position of the image in the canvas.

By using anchor parameters, we can align the text and images in any direction. For now, we will create an image label by using the Label function such that,

Label(root, text= " ", other Options(color, width,height,..))

After creating the image label using the above function, we will adjust its position using the ‘anchor’ property. Since we have to place the image at the center, we will pass the value of anchor as “CENTER”.


#import the tkinter library in the notebook

from tkinter import *
#creating an instance of the tkinter canvas
win= Tk()
#define the size of the window

#define the image label having some properties

label_img= Label(win, text= "Hello World", font= "sans-serif",relief=
"solid",width= 20, height= 8, anchor= CENTER)
#displaying the canvas without closing the window

Running the above snippet will generate the output and place the image at the center of the canvas.


Updated on 04-Mar-2021 13:56:43