[Tutor] tkinter canvas
Mr Gerard Kelly
s4027340 at student.uq.edu.au
Fri Jan 16 02:00:30 CET 2009
wow, that's excellent, thanks so much.
I haven't got a clue how lambda functions work, but they seem pretty
useful, so I'll try to figure them out.
----- Original Message -----
From: Kent Johnson <kent37 at tds.net>
Date: Thursday, January 15, 2009 10:24 pm
Subject: Re: [Tutor] tkinter canvas
> On Thu, Jan 15, 2009 at 12:41 AM, Mr Gerard Kelly
> <s4027340 at student.uq.edu.au> wrote:
>
> > I want to be able to bind these boxes to an event - so that I can
> either> click on them, or hold the mouse cursor over them, and have
> them change
> > color.
>
> Here is a version of your program that binds the Enter and Leave
> events to each box and changes the box color when the mouse is over
> it:
>
> #########################
>
> from Tkinter import *
>
> master = Tk()
>
> numboxes=6
>
> width=40*(numboxes+2)
> height=200
> w = Canvas(master, width=width, height=height)
> w.pack()
>
> size=width/(numboxes+2)
>
> box=[0]*numboxes
>
> def enter(e, i):
> e.widget.itemconfigure(box[i], fill='red')
>
> def leave(e, i):
> e.widget.itemconfigure(box[i], fill='blue')
>
> for i in range(numboxes):
> box[i]=w.create_rectangle((1+i)*40, 40, (2+i)*40, height-40,
> fill="blue") w.tag_bind(box[i], '<Enter>', lambda e, i=i:
> enter(e, i))
> w.tag_bind(box[i], '<Leave>', lambda e, i=i: leave(e, i))
>
> mainloop()
>
> #######################
>
> The 'i=i' in the lambda is needed due to the (surprising) way that
> variables are bound to closures; without it, every event would be
> bound to the same value of i. Some explanation here:
> http://code.activestate.com/recipes/502271/
>
> Kent
>
More information about the Tutor
mailing list