Search code examples
pythoncanvastexttkinterposition

Python canvas text position changes with font


I'm fairly new to Python and GUI programming, but while trying to create a simple canvas program I ran into the following problem: When I use the create_text function(x, y etc.) it creates the text nicely at (x, y), but when I add a font the text shifts to the left and is no longer created at (x, y).

Can somebody tell me how I can fix this, and get the text at (60, 40) (see code)

from tkinter import *

class CanvasShapes:
    def __init___(self):
        master = Tk()

        self.c1 = Canvas(master, width = 200, height = 100)
        self.c1.grid(columnspan = 5)

        #there are more buttons, but this is the only relevant one for this problem
        Button(master, text = "String", command = self.String).grid(row = 1, column = 3)

    def String(self):
        self.c1.create_text(60, 40, text = "Hi, I am a string", font = "Times 16 bold underline")

def main():
    Canvas1 = CanvasShapes()

main()

Solution

  • By default, the x,y represents the center point of the text. If you make the font larger or smaller, the center remains the same but the edges will change depending on the size of the text.

    Add anchor='nw' to the create_text command to have the coordinates reoresent the upper-left (northwest) corner of the text.