Tracking Mouse Actions for Many Canvas Objects

April 15, 1998 | Fredrik Lundh

Instead of binding event handlers to each and every item, you can use a single event handler and then use find_withtag(CURRENT) to get the target item. An example:

from Tkinter import *
from random import randint

root = Tk()

canvas = Canvas(root, width=200, height=200)

def click(event):
    if canvas.find_withtag(CURRENT):
        canvas.itemconfig(CURRENT, fill="blue")
        canvas.itemconfig(CURRENT, fill="red")

for i in range(100):
    x, y = randint(0, 200-1), randint(0, 200-1)
    canvas.create_oval(x-5, y-5, x+5, y+5, fill="red")

canvas.bind("<Button-1>", click)


A Django site. rendered by a django application. hosted by webfaction.