How to get the coordinates of an object in a Tkinter canvas?


Tkinter Canvas Widget provides GUI features to an application. It can be used to draw shapes, animate objects, and configure the existing items in a canvas. Whenever we create shapes, we have to provide the size and coordinates of the shapes in the Canvas item constructor. In order to return the coordinates of an item on the Canvas, we can use the coords(item) method. It returns a list with the coordinates of the shapes in the canvas widget.


from tkinter import *
#Create an instance of tkinter frame
win = Tk()
#Set the geometry of Tkinter frame

# Initialize a Canvas Object
canvas = Canvas(win, width= 500, height= 300)

# Draw an oval inside canvas object
c= canvas.create_oval(100,10,410,200, outline= "red", fill= "#adf123")
canvas.pack(expand= True, fill=BOTH)

#Get and Print the coordinates of the Oval
print("Coordinates of the object are:", canvas.coords(c))


If we execute the above code, it will display a window with an oval inside it.

Along with that, the code will return and print the coordinates of the object on the console.

Coordinates of the object are: [100.0, 10.0, 410.0, 200.0]
Published on 25-May-2021 09:28:40