Python Tkinter How to fit text in canvas

1.2k Views Asked by At

A text item is placed in the center of a canvas with fixed dimensions. The size of this text should now be adjusted, so that it just fits in the canvas: This means that the text shouldn't be wider or higher than the canvas, but either it's width or length is equal to the width or length of the canvas.

The specific problem I'm struggling with is how to find the actual width(in pixels, of course) of the text item.

Any ideas? Thanks in advance!

1

There are 1 best solutions below

0
On BEST ANSWER

The actual width and height of the text can be retrieved with the bbox method, which returns the bounding box of the text. The bounding box returns the coordinates of the upper-left and lower-right area used by the canvas item.

For example:

...
text = canvas.create_text(100,100, text="Hello, world")
...
x1,y1,x2,y2 = canvas.bbox(text)
width = x2-x1
height=y2-y1