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

Question:

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 (Why, you ask? Too lazy).

Asked By: willywillycow

||

Answers:

You can use .moveto(item_id, x, y) to move the canvas item to absolute position (x, y).

Answered By: acw1668

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
Answered By: Bryan Oakley
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.