Ben Bush wrote:
I tested the following code and wanted to make oval 2 become red after
I hit the enter key but though the code did not report error, it did
not change.
from Tkinter import *
root=Tk()
canvas=Canvas(r oot,width=100,h eight=100)
canvas.pack()
canvas.create_o val(10,10,20,20 ,tags='oval1',f ill='blue')
canvas.create_o val(50,50,80,80 ,tags='oval2',f ill='yellow')
def turnRed(self, event):
event.widget["activeforegrou nd"] = "red"
self.button.bin d("<Enter>", self.turnRed)
canvas.tag_bind ('oval2',func=t urnRed)
root.mainloop()
The <Enter> event is triggered when you enter a shape with the mouse
pointer, not when you press the key.
It seems you cannot associate keypress events with shapes, only with the
whole canvas.
Here is some code for you to play with.
import Tkinter
def turnRed(event):
canvas.itemconf igure("oval2", fill="red")
def turnYellow(even t):
canvas.itemconf igure("oval2", fill="yellow")
def keypress(event) :
print "you pressed return or enter"
if "oval2" in canvas.gettags( "current"):
canvas.itemconf igure("current" , fill="green")
root = Tkinter.Tk()
canvas = Tkinter.Canvas( root, width=100, height=100)
canvas.pack()
canvas.create_o val(10, 10, 20, 20, tags="oval1", fill="blue")
canvas.create_o val(50, 50, 80, 80, tags="oval2", fill="yellow")
canvas.tag_bind ("oval2", "<Enter>", turnRed)
canvas.tag_bind ("oval2", "<Leave>", turnYellow)
canvas.bind("<K ey-Return>", keypress)
canvas.bind("<K ey-KP_Enter>", keypress)
canvas.focus_se t()
root.mainloop()
Try pressing Return with the mouse pointer over oval2 and elsewhere on the
canvas.
Peter