如何在 Tkinter 中将点击事件绑定到 Canvas?

How to bind a click event to a Canvas in Tkinter?

我只是想知道是否可以使用 Tkinter 将点击事件绑定到 canvas。

我希望能够单击 canvas 上的任意位置并将对象移动到它。我可以提出议案,但我还没有找到将点击绑定到 canvas.

的方法

直接取自 Effbot tutorial 事件的示例。

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

更新: 如果 window/frame 包含一个像 Tkinter.Entry 小部件这样的小部件,则上面的示例将不适用于 'key' 事件键盘焦点。放:

canvas.focus_set()
'callback' 函数中的

会给 canvas 小部件键盘焦点,并会导致后续键盘事件调用 'key' 函数(直到其他小部件获得键盘焦点)。 =14=]