Detecting collisions between items
As a continuation of the preceding recipe, we can detect whether a rectangle item overlaps with another one. In fact, this can be achieved, assuming that we are working with shapes contained in rectangular boxes, using the find_overlapping()
method from the Canvas
class.
Getting ready
This application extends the preceding one by adding four green rectangles to the canvas and highlighting the one that is touched by a blue rectangle moved using the arrow keys:

How to do it...
Since this script has many similarities with the preceding one, we marked the parts of the code that create the four rectangles and invoke the canvas.find_overlapping()
method:
import tkinter as tk class App(tk.Tk): def __init__(self): super().__init__() self.title("Detecting collisions between items") self.canvas = tk.Canvas(self, bg="white") self.canvas.pack() self.update() self.width = w = self.canvas.winfo_width() self.height...