change color

Peter Otten __peter__ at web.de
Mon Dec 5 04:06:28 EST 2005


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(root,width=100,height=100)
> canvas.pack()
> canvas.create_oval(10,10,20,20,tags='oval1',fill='blue')
> canvas.create_oval(50,50,80,80,tags='oval2',fill='yellow')
> def turnRed(self, event):
>     event.widget["activeforeground"] = "red"
>     self.button.bind("<Enter>", self.turnRed)
> canvas.tag_bind('oval2',func=turnRed)
> 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.itemconfigure("oval2", fill="red")

def turnYellow(event):
    canvas.itemconfigure("oval2", fill="yellow")

def keypress(event):
    print "you pressed return or enter"
    if "oval2" in canvas.gettags("current"):
        canvas.itemconfigure("current", fill="green")

root = Tkinter.Tk()

canvas = Tkinter.Canvas(root, width=100, height=100)
canvas.pack()
canvas.create_oval(10, 10, 20, 20, tags="oval1", fill="blue")
canvas.create_oval(50, 50, 80, 80, tags="oval2", fill="yellow")

canvas.tag_bind("oval2", "<Enter>", turnRed)
canvas.tag_bind("oval2", "<Leave>", turnYellow)

canvas.bind("<Key-Return>", keypress)
canvas.bind("<Key-KP_Enter>", keypress)

canvas.focus_set()
root.mainloop()

Try pressing Return with the mouse pointer over oval2 and elsewhere on the
canvas. 

Peter




More information about the Python-list mailing list