如何将事件绑定到 Canvas 项目?

发布于 2024-09-01 09:04:17 字数 154 浏览 2 评论 0原文

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉殇 2024-09-08 09:04:17

要与 Canvas 对象中包含的对象进行交互,您需要使用 tag_bind() ,其格式如下:tag_bind(item, event=None, callback=None, add=None)

item 参数可以是标签,也可以是 id。

下面是一个例子来说明这个概念:

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

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)

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文