Moving canvas items
Once placed, canvas items can be moved to a certain offset, without having to specify the absolute coordinates.
When moving canvas items, it is usually relevant to calculate its current position, for instance, to determine whether they are placed inside a concrete canvas area, and restrict their movements so that they always stay within that area.
How to do it...
Our example will consist of a simple canvas with a rectangle item, which can be moved horizontally and vertically using the arrow keys.
To prevent this item from moving outside of the screen, we will limit its movements inside the canvas dimensions:
import tkinter as tk class App(tk.Tk): def __init__(self): super().__init__() self.title("Moving canvas items") self.canvas = tk.Canvas(self, bg="white") self.canvas.pack() self.update() self.width = self.canvas.winfo_width() self.height = self.canvas.winfo_height() self.item = self.canvas.create_rectangle...