change color

B

Ben Bush

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

Peter Otten

Ben said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top