问题
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:
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=""
).
来源:https://stackoverflow.com/questions/43824005/tkinter-bind-to-arc