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

六眼飞鱼酱① 提交于 2019-12-17 19:35:06

问题


I was just wondering if there was any possible way to bind a click event to a canvas in 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, yet I have not found a way to bind a click event on a canvas.


回答1:


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



来源:https://stackoverflow.com/questions/29211794/how-to-bind-a-click-event-to-a-canvas-in-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!