Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to create some text in a canvas:

myText = self.canvas.create_text(5, 5, anchor=NW, text="TEST")

Now how do I find the width and height of myText?

like image 419
Matt Gregory Avatar asked Sep 21 '08 20:09

Matt Gregory


People also ask

What is the difference between Canvas and frame in Tkinter?

A Frame is designed to be a parent container of other widgets. A Canvas is like a canvas that you can draw somethings on it like lines, circles, text, etc. A Canvas can be used as a parent container as well but it is not designed for that at the first place.

Is Canvas a widget in Tkinter?

The Canvas widget supplies graphics facilities for Tkinter. Among these graphical objects are lines, circles, images, and even other widgets. With this widget it's possible to draw graphs and plots, create graphics editors, and implement various kinds of custom widgets.

What is a Tkinter Canvas?

A tkinter canvas can be used to draw in a window. Use this widget to draw graphs or plots. You can even use it to create graphical editors. You can draw several widgets in the canvas: arc bitmap, images, lines, rectangles, text, pieslices, ovals, polygons, ovals, polygons, and rectangles.


2 Answers

bounds = self.canvas.bbox(myText)  # returns a tuple like (x1, y1, x2, y2)
width = bounds[2] - bounds[0]
height = bounds[3] - bounds[1]

See the TkInter reference.

like image 59
skymt Avatar answered Sep 24 '22 21:09

skymt


This method seemed to work well if all you are interested in is the width and height of the canvas being considered, using the bounds of the box and then checking the differential works just as well if you want to do it that way.

width = myText.winfo_width()  
height = myText.winfo_height()
like image 36
user3754203 Avatar answered Sep 25 '22 21:09

user3754203