23

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.

Community
  • 1
  • 1
lukejano
  • 301
  • 1
  • 4
  • 12
  • 2
    Try [here](http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm) for a good read on Tkinter events. – Malik Brahimi Mar 23 '15 at 13:44
  • 3
    This question is not to broad and should be reopened. (It could be a duplicate but that not important. I suspect that someone, or worse, a program saw the word 'wondering' and thought the question might be broad – Ribo Mar 18 '19 at 20:33

1 Answers1

37

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).

Henry
  • 3,472
  • 2
  • 12
  • 36
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
  • 3
    Why does the `callback` function need a `focus_set()`? – martineau Mar 23 '15 at 13:55
  • 1
    @MalikBrahimi You don't need at all to set the focus to the frame. You associated the `""` event with the frame, therefore `callback` will be called only when you click the frame area and nothing more. – nbro Mar 23 '15 at 14:35
  • 2
    Also, the OP is asking for binding a click event on a Canvas, not on a frame. If you want me to remove the down vote, you should modify your code and notify me. – nbro Mar 23 '15 at 15:50
  • It is just as easy to put a canvas as it is a frame. – Malik Brahimi Mar 23 '15 at 16:24
  • @MalikBrahimi At this point, I would invite you kindly to show a complete example of what the OP is asking, means that when he clicks the canvas a certain objects moves in that position, if I understood well the request. – nbro Mar 23 '15 at 16:35