Skip to content
Advertisement

How do I get text to be centered in a Tkinter Canvas?

I am making Checkers and am using an asterisk to mark the kings. I need the asterisk to be centered in the middle of the canvas. I made this example to show what’s going wrong:

from tkinter import *

class MyCanvas(Canvas):

    def __init__(self,master):
        Canvas.__init__(self,master,width=100,height=100,bg='blue')
        self.grid()
    
    def add_asterisk(self):
        self.create_text(50,50,text="*",fill="black",font=('Arial',80),anchor='center')


root = Tk()
root.title('Example')
myCanvas = MyCanvas(root)
myCanvas.add_asterisk()
myCanvas.mainloop()

The asterisk looks like it’s centered on the horizantal axis, but it is too high on the vertical one. I’m placing it at (50,50), since the canvas is 100×100. Thanks in advance!

Advertisement

Answer

It may not look like it but the text is centered. You are doing it correctly.

More precisely, the space allocated for the character is centered. In every font, some characters appear low in the space they are given (for example, an underscore or comma), some are high (for example, quote marks and apostrophes), and some are centered vertically (for example, a hyphen).

This is not something you can control, other than to find a font that draws asterisks in the middle of the line.

In the following three screenshots I show three different characters, where the only difference in the code is the character itself. All other options are identical. I’ve drawn a white box around the space allocated for the character.

You can see that an underscore is at the very bottom of the space, a hyphen is roughly in the middle, and the asterisk is higher up. You can also see that in all three cases, the area reserved for the character is centered in the same spot.

screenshot with underscore screenshot with hyphen screenshot with asterisk

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement