How do I find out the size of a canvas item in Tkinter?

TkinterServer Side ProgrammingProgramming

To find the minimum height and width of canvas items, we can use the bounding box property of Canvas. Basically, a bounding box property enables the canvas item to return the position inside the canvas. Initially, every item in the bbox(item) method defines the minimum and maximum width and height of the item.

Example

#Import required libraries
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
#Define the geometry of the window
win.geometry("750x250")
#Initialize a Canvas
canvas= Canvas(win, width= 600, height= 200)
#Add a text inside the Canvas
text= canvas.create_text(300,20, text= "This is a New Line Text", font=16,anchor= "n")
canvas.pack()
#Finding the width and height of canvas Items
bounds= canvas.bbox(text)
width= bounds[3]-bounds[0]
height= bounds[3]- bounds[1]
print(width)
print(height)

win.mainloop()

Output

Running the above code will display a window that contains a Canvas Item (Text). It will print the size of the item in the terminal.

The size of the canvas item will be,

-154
23
raja
Published on 03-May-2021 09:07:17
Advertisements