Search code examples
pythontkinter

how to change the position of a canvas object after you created it in Python Tkinter?


So I was wondering there is a way to directly set the x and y coordinate of a canvas object after you created it. I know move method but it only changes the coordinate by the value, but not directly setting it, and I don’t want to make a function just for subtracting the target coordinate by the current coordinate and moving it by the value.


Solution

  • The canvas has multiple methods. You can use coords to change the coordinates (which can both move and resize the object), move to move an item a relative distance in the x and y direction, moveto to move the item to an absolute position.

    id = canvas.create_rectangle(10,10,100,100)
    canvas.move(id, 2, 2)      # move 2 pixels right and down
    canvas.moveto(id, 20, 20)  # to rectangle to position 20,20
    canvas.coords(id, 100, 100, 120, 120)  # redraw the rectangle at the given coordinates