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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29211794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:12:21  来源:igfitidea点击:

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

pythonpython-2.7tkintertkinter-canvas

提问by lukejano

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

我只是想知道是否有任何可能的方法将点击事件绑定到 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.

我希望能够单击画布上的任意位置并将对象移动到它。我能够做出动作,但我还没有找到在画布上绑定点击事件的方法。

采纳答案by Malik Brahimi

Taken straight from an example from an Effbot tutorialon events.

直接取自 Effbot事件教程中的示例。

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:

在此示例中,我们使用框架小部件的 bind 方法将回调函数绑定到名为 的事件。运行此程序并在出现的窗口中单击。每次单击时,控制台窗口都会打印一条消息,例如“在 44 63 处单击”。键盘事件被发送到当前拥有键盘焦点的小部件。您可以使用 focus_set 方法将焦点移动到小部件:

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:

更新:如果窗口/框架包含像具有键盘焦点的 Tkinter.Entry 小部件这样的小部件,则上面的示例将不适用于“键”事件。推杆:

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

在“回调”函数中,会给画布小部件键盘焦点,并导致后续键盘事件调用“键”函数(直到其他一些小部件获得键盘焦点)。