Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a click event to a Canvas in Tkinter? [closed]

Tags:

I was just wondering if there was any possible way to bind a click event to a canvas using Tkinter.

I would like to be able to click anywhere on a canvas and have an object move to it. I am able to make the motion, but I have not found a way to bind clicking to the canvas.

like image 375
lukejano Avatar asked Mar 23 '15 13:03

lukejano


People also ask

How do you bind a click event to a canvas in Tkinter?

In order to bind a click event, we can use the tag_bind() method and use the delete(image object) to delete the image.

How do I handle the window close event in Tkinter?

To handle the window close event in Tkinter with Python, we call the root. protocol method with the 'WM_DELETE_WINDOW' event. to call root. protocole with "WM_DELETE_WINDOW" to add a close window handler.

How do you bind an event in Python?

Binding Mouse click events In the below example we call the events to display the left-button double click, right button click and scroll-button click to display the position in the tkinter canvas where the buttons were clicked.

Which method is used to associate a Tkinter mouse event with its event handler?

Use the bind() method to bind an event to a widget. Tkinter supports both instance-level and class-level bindings.


1 Answers

Taken straight from an example from an Effbot tutorial on events.

In this example, we use the bind method of the frame widget to bind a callback function to an event called . Run this program and click in the window that appears. Each time you click, a message like “clicked at 44 63” is printed to the console window. Keyboard events are sent to the widget that currently owns the keyboard focus. You can use the focus_set method to move focus to a widget:

from Tkinter import *  root = Tk()  def key(event):     print "pressed", repr(event.char)  def callback(event):     print "clicked at", event.x, event.y  canvas= Canvas(root, width=100, height=100) canvas.bind("<Key>", key) canvas.bind("<Button-1>", callback) canvas.pack()  root.mainloop() 

Update: The example above will not work for 'key' events if the window/frame contains a widget like a Tkinter.Entry widget that has keyboard focus. Putting:

canvas.focus_set() 

in the 'callback' function would give the canvas widget keyboard focus and would cause subsequent keyboard events to invoke the 'key' function (until some other widget takes keyboard focus).

like image 139
Malik Brahimi Avatar answered Sep 29 '22 12:09

Malik Brahimi