I was wondering how to measure the width of a text in tkinter canvas. I have a text displayed somewhere:
myCanvas.create_text(400,410, text="This is my text", tags="my_tag")
and at some point there is a shape (polygon line) that may overlap when the text gets longer (text will be changed with .itemconfigure()
). In this case I wanted to break the text in lines, which works well with the width
option.
To figure out if objects overlap there are a couple of possible methods: find_overlapping()
or find_enclosed()
, however, they do require 4 coordinates and myCanvas.coords("my_tag")
only returns 2 coordinates. How could I figure out the other x2
, y2
?
An alternative was to use find_closest()
, however, there are a bunch of shapes closer than the overlapping one, so that is not accurate.
Another alternative was that I could figure out the intersecting coordinate and then just take the distance to the x coordinate of the text and double that as a width (since text gets drawn from the center), for example:
intersection point at (350,405)
=> width = 2 * (400-350)
However, since the shape is a line (part of a polygon) that goes diagonal, I'm not sure how get the intersection point other than having a loop that creates a line that slowly increases till it overlaps with an object, for example:
text_center = (400,410)
start_x = text_center[0]
start_y = text_center[1]
extender = 1
while(myCanvas.find_overlapping(start_x, start_y, start_x entender, start_y == ())
myCanvas.delete("mytestline")
extender = 1
myCanvas.create_line(start_x, start_y, start_x extender, start_y, tags="mytestline")
overlapping_point = (start_x extender, start_y)
Is there an easier way?
CodePudding user response:
The bbox
method will return the bounding box of any item or group of items on the canvas. The bounding box is the smallest rectangle that contains the elements, give or take a pixel or two. The returned value is a tuple of the two coordinates.
The following example creates a text item, gets and displays the bounding box, and also uses the coordinates to draw a rectangle around the text so you can visually see that the numbers are correct.
import tkinter as tk
root = tk.Tk()
myCanvas = tk.Canvas(root)
myCanvas.pack(fill="both", expand=True)
item_id = myCanvas.create_text(100,50, text="This is my text", tags="my_tag")
bbox = myCanvas.bbox(item_id)
myCanvas.create_rectangle(bbox, outline="red")
myCanvas.create_text(100, 70, text=f"bbox: {bbox}")
root.mainloop()