

This means that Tkinter has registered a click event for the canvas object and the element will be triggered.
#TKINTER GET MOUSE COORDINATES ON CANVAS CODE#
You will notice when running this code that when we click the command line output will be as follows. In both of these examples we change the oval to look like this when it is clicked. Print('Clicked object at: ', event.x, event.y) We can also use this method to find the correct item and change that items colour to blue. The canvas object also has a method built in called find_closest() that can be used to find the closest object to the item that was part of the event. Print('Clicked object at: ', (event.num), event.num) This gives us a handy way of grabbing the element that was clicked and changing it's colour to blue. The event object sent to the event contains information about where the event happened on the canvas, but also what object triggered the event stored in the "num" property. _bind(oval_element, '', self.object_click_event) In the code below we are using the tag_bind() method to tag the primary button click event "Button-1" to the callback of object_click_event method on the white oval. The most common way to find this ID is by capturing the result of the Canvas element creation method. This method also takes the ID or tag of the element we want to bind the event to. To create an event against an element inside the canvas we need to use the tag_bind() method. This type of event is especially useful for keyboard shortcuts in your application.

This will attach the event to the application level, rather than at the element level, meaning that this event will trigger even if the element we used doesn't have focus. We can also create the event using the bind_all() method. Here is an example of the output we see if the canvas element is clicked. Print('Clicked canvas: ', event.x, event.y, event.widget) All we do in this method is to print out that a click event happened, what the coordinates of that event were, and the Tkinter widget that triggered the event. The self.canvas_click_event method is a method within the same CanvasEvents object defined at the top. To bind the mouse button being clicked to the canvas element we would use the bind() method like this.
#TKINTER GET MOUSE COORDINATES ON CANVAS HOW TO#
In this article I will address how to set events, how to react to their output and how to find out what element triggered the event.

There are a few things to take into account when binding events like what events to trigger on and how to find out what item triggered what event. There are lots of ways to draw objects using the Tkinter Canvas element, but making the canvas elements interactable adds a lot to the applications you create.
