如何在 Tkinter 中将点击事件绑定到 Canvas? [英] How to bind a click event to a Canvas in Tkinter?

查看:37
本文介绍了如何在 Tkinter 中将点击事件绑定到 Canvas?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道是否有任何可能的方法使用 Tkinter 将点击事件绑定到画布.

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.

推荐答案

直接取自 Effbot 的示例 关于事件的教程.

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

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

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

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

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

这篇关于如何在 Tkinter 中将点击事件绑定到 Canvas?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆