Tkinter bind to arc

2019-09-14 01:55发布

I'm writing a simple noughts - and - crosses game in python using Tkinter and want to have the Os show only when you hover over them. To do this, I know I need to add an event binding, but don't know how because when I create a circle (arc) I don't get an object returned but an id number instead. How can I use this id number to create an event binding?

1条回答
来,给爷笑一个
2楼-- · 2019-09-14 02:45

Instead of using the ID number to create an event binding, I would recommend using a tag system to go about this. When creating your oval object, e.g. canvas.create_oval(100, 100, 200, 200), add ,tag="tag_name" inside the parenthesis to apply a tag to your created object. You can then bind to this tag explicitly, for example using the tag_bind function of the canvas.

You could create something like this, after creating an oval with tag "oval":

canvas.tag_bind("oval", "<ButtonPress-1>", pressed_oval)

This would then call your function called pressed_oval() only when the user clicks on the object you gave the tag "oval" (and passing event to it).

Hopefully this helps you get started!

I would note that for tag_bind to work, the object still has to be on the canvas, so instead of changing the state of your ovals to hidden or pack forgetting them, just switch the ovals fill between your colour and nothing (fill="").

查看更多
登录 后发表回答