Binding events to canvas items
So far, we have seen how to bind events to widgets; however, it is also possible to do so for canvas items. This helps us to write more specific and simpler event handlers, instead of binding all the types of events we want to process on the Canvas
instance and then determining which action has to be applied according to the affected item.
Getting ready
The following application shows how to implement the drag and drop functionality on canvas items. This is a common functionality that serves to illustrate how this approach can simplify our programs.
How to do it...
We will create a couple of items that can be dragged and dropped with the mouse—a rectangle and an oval. The different shapes help us to note how the click events are correctly applied to the corresponding item, even though the items are placed overlapping each other:
import tkinter as tk class App(tk.Tk): def __init__(self): super().__init__() self.title("Drag and drop") ...