Text position in tkinter

08 Dec, 2016

Drew M writes:

I have a question I am sure I don't know :) In tkinter I am creating a game and can't figure out how to set dimensions for text. I need it on the middle. My canvas is 1000 by 1000 so I divided in half. Which is of course 500. Now again, my question is how to put it there.

Adding text to a canvas is straightforward (similar to adding any other item, such as a line, or a rectangle). You say "middle" and not "center", so I assume you don't want the text directly in the center of the canvas? I've defined a smaller canvas here, but the principle is the same:

from tkinter import *
tk = Tk()
canvas = Canvas(tk, width=100, height=100, bd=0, highlightthickness=0)
canvas.create_text(50, 50, text='text')
canvas.pack()
tk.update()

text position center

So if you don't want the center, I'm guessing your problem is that this code...

from tkinter import *
tk = Tk()
canvas = Canvas(tk, width=100, height=100, bd=0, highlightthickness=0)
canvas.create_text(50, 0, text='text')
canvas.pack()
tk.update()

...(with coordinates of 50, 0) results in partially obscured text:

text position middle

The answer, is to use the named parameter anchor in the create_text function:

canvas.create_text(50, 0, text='text', anchor=N)

The anchor parameter controls the positioning of an item in terms of its coordinates. The default value is CENTER (so using this puts the center of the text at the coordinates (50, 0) in the earlier example), but you can also use NW, N, NE (effectively top-left, top-middle, top-right), W, E (left and right), and SW, S, SE (bottom-left, bottom-middle, bottom-right). So N puts the top and middle point of the text at the coordinates (50, 0), like so:

text position N

I hope that helps.