简体   繁体   中英

Python Tkinter How to fit text in canvas

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM