jdoe jdoe - 4 months ago 27
Python Question

Tkinter, Label/Text in canvas.rectangle [python]

I need to place a text/label centred in a canvas rectangle in tkinter.

First I have a canvas covering the whole screen(800, 600).
And then I have a couple of rectangles which I made using the:


The first X of the first rectangle is 275 and the second X is 525.

The first Y of the first rectangle is 265 and the second Y is 315.

menuBtn1 = canvas.create_rectangle(275, 165, 525, 215, fill="#C2B6BF")

Now how I can place a text/label in the center of this rectangle?


You should use create_text. As it says in the link in the description of the position parameter:

By default, the text is centered on this position. You can override this with the anchor option. For example, if the coordinate is the upper left corner, set the anchor to NW.

So this should be what you want:

mylabel = canvas.create_text((400, 190), text="Label text")