Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind events to Canvas items?

If I'm using a canvas to display data and I want the user to be able to click on various items on the canvas in order to get more information or interact with it in some way, what's the best way of going about this?

Searching online I can find information about how to bind events to tags but that seems to be more indirect then what I want. I don't want to group items with tags, but rather have specific function calls when the user clicks specific items on the canvas.

like image 931
Ian Avatar asked May 07 '10 07:05

Ian


People also ask

How to bind canvas in tkinter?

Tkinter events can be bound with the widgets to perform a set of operations on the widgets. To be more specific, we can also bind an event handler to Canvas Items by using bind(<Button>, callback) method. Binding the event with the canvas item makes a canvas item dynamic which can be customized by event handlers.

How do you bind a canvas?

Example. In this example, we will add an image inside the canvas widget and will bind a button object to remove the image from the canvas. In order to bind a click event, we can use the tag_bind() method and use the delete(image object) to delete the image.


1 Answers

To interact with objects contained in a Canvas object you need to use tag_bind() which has this format: tag_bind(item, event=None, callback=None, add=None)

The item parameter can be either a tag or an id.

Here is an example to illustrate the concept:

from tkinter import *   def onObjectClick(event):                       print('Got object click', event.x, event.y)     print(event.widget.find_closest(event.x, event.y))  root = Tk() canv = Canvas(root, width=100, height=100) obj1Id = canv.create_line(0, 30, 100, 30, width=5, tags="obj1Tag") obj2Id = canv.create_text(50, 70, text='Click', tags='obj2Tag')  canv.tag_bind(obj1Id, '<ButtonPress-1>', onObjectClick)        canv.tag_bind('obj2Tag', '<ButtonPress-1>', onObjectClick)    print('obj1Id: ', obj1Id) print('obj2Id: ', obj2Id) canv.pack() root.mainloop() 
like image 91
tdedecko Avatar answered Oct 08 '22 09:10

tdedecko