如何将事件绑定到 Canvas 项目? [英] How to bind events to Canvas items?

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

问题描述

如果我使用画布来显示数据,并且我希望用户能够点击画布上的各种项目以获取更多信息或以某种方式与之交互,那么最好的方法是什么这个?

If I'm using a canvas to display data and I want the user to be able to click on various items on the canvas in order to get more information or interact with it in some way, what's the best way of going about this?

在线搜索我可以找到有关如何将事件绑定到标签的信息,但这似乎比我想要的更间接.我不想用标签对项目进行分组,而是在用户点击画布上的特定项目时调用特定的函数.

Searching online I can find information about how to bind events to tags but that seems to be more indirect then what I want. I don't want to group items with tags, but rather have specific function calls when the user clicks specific items on the canvas.

推荐答案

要与包含在 Canvas 对象中的对象进行交互,您需要使用具有此功能的 tag_bind()格式:tag_bind(item, event=None, callback=None, add=None)

To interact with objects contained in a Canvas object you need to use tag_bind() which has this format: tag_bind(item, event=None, callback=None, add=None)

item 参数可以是标签或 ID.

The item parameter can be either a tag or an id.

这里有一个例子来说明这个概念:

Here is an example to illustrate the concept:

from tkinter import * 

def onObjectClick(event):                  
    print('Got object click', event.x, event.y)
    print(event.widget.find_closest(event.x, event.y))

root = Tk()
canv = Canvas(root, width=100, height=100)
obj1Id = canv.create_line(0, 30, 100, 30, width=5, tags="obj1Tag")
obj2Id = canv.create_text(50, 70, text='Click', tags='obj2Tag')

canv.tag_bind(obj1Id, '<ButtonPress-1>', onObjectClick)       
canv.tag_bind('obj2Tag', '<ButtonPress-1>', onObjectClick)   
print('obj1Id: ', obj1Id)
print('obj2Id: ', obj2Id)
canv.pack()
root.mainloop()

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

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