[Tutor] I'm just full of questions today

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Sat, 28 Oct 2000 22:04:42 -0700 (PDT)


On Sun, 29 Oct 2000, wheelege wrote:

>   I've been trying to get global variables to help me, the way I've
> been getting around it is to pass local variables to a function
> through arguments - but that is going to get very unwieldy and messy.  

Global variables... nooo!  *grin*

One way to create callbacks that use local variables is to do a
lambda.  For example:

###
def hi(name):
     print "Hello " + name + "!"

# later on...

    b = Button(root, text='hi', command=
                 lambda name="wheelege": hi(name))
###

Yes, this is admittedly ugly.  What the lambda part is doing is creating
an anonymous function with a default argument --- this gets around the
fact that callbacks need to be functions that don't take arguments.

If you're new to Python, this is probably the first time you've seen this.  
If so, email us again, and one of the tutors can give a more leisurely
explanation of lambda and function passing.


> So, I decided to change my little section of code to give me an error
> about using a local variable before assignment.  I think the error is
> because I tell it to change the value of the 's' variable to 's' + 1,

Don't forget about the 'global' thing that you asked about last time.


> And, as a side note - why isn't my window title 'yo'?

That part I'm not quite sure.  You might want to look at the Tkinter
documentation and check how to change the titles of frames.  I'm not sure
that saying f.title = "yo" is enough; you can say f.foobarish = "yo" and
it wouldn't complain, but at the same time, it wouldn't do anything
either.