11

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
Matt Gregory
  • 8,074
  • 8
  • 33
  • 40

2 Answers2

22
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.

martineau
  • 119,623
  • 25
  • 170
  • 301
skymt
  • 3,199
  • 21
  • 13
  • In newer versions of tkinter you can provide an "angle" to create_text. If angle != 0 your solution is not correct anymore, because the bbox fits the whole rotated text. In this case or generally you can use the font-metrics: `f=self.canvas.itemcget(myText, "font") font = tk.font.Font(font=font.split(" ")) height = font.metrics("linespace")` – Stefan Jun 06 '21 at 09:54
4

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()
user3754203
  • 139
  • 4
  • 8
  • 3
    `myText`, at least in the given example is an `int`. The lines you gave would only cause an **AttributeError** to be raised. – Adrian Castravete Oct 17 '16 at 11:14
  • 2
    Wondering why this is upvoted so much since the comment above is correct: I'm just getting attribute errors. – Bram Vanroy May 25 '20 at 15:16
  • 1
    This works in case `myText` is a widget. But **myText is not a separate widget but an id of an item in a Canvas** (i.e. an integer which refers to an item of the Canvas). You are trying to use the `.winfo_width()` method on that integer => you get AttributeError. – Demian Wolf Dec 19 '20 at 23:04