[Tutor] Buttons automatically executing

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Jun 15 23:33:04 CEST 2005



On Wed, 15 Jun 2005, Phillip Hart wrote:

> Thanks for taking the time to read this.
>
> Excuse me if this falls under the boundaries of a "newbie" question, as
> I am a self-taught programmer.

Hi Phillip,

It's a "newbie" question.  But that's perfectly ok.  *grin*


> While using Tkinter to create buttons, something unexpected happens when
> the button commands call functions. Namely, when I run the following, it
> immediately executes the print statements without the button ever being
> pressed. Additionally, pressing the button once the Tk window is up will
> not activate the button.

The issue is that there's a difference between calling a function, and
getting a function value.  Let's go through an example to get started:


For example, let's say that we do have that 'location' function defined:

#######
>>> def location(x, y):
...     print "I am in row", x, "and column", y
...
#######



A function value is what we get when we don't use parentheses:

#######
>>> location
<function location at 0x64c30>
#######


And this thing can be handled just like any other value in Python: we can
pass it around and put it in lists:

#######
>>> somelist = [location, location, location]
>>> somelist
[<function location at 0x64c30>, <function location at 0x64c30>, <function
location at 0x64c30>]
#######



One neat thing that you already know about functions is that they can be
called.  You're used to doing something like this:

#######
>>> location(3, 4)
I am in row 3 and column 4
#######


but we can also do something like this:

#######
>>> somelist[0]
<function location at 0x64c30>
>>> somelist[0](2, 3)
I am in row 2 and column 3
#######

That is, 'somelist[0]' is a function value, and when we use parens next to
it '(2, 3)', then we fire off that function value with those two
arguments.

Does this make sense so far?



When we're constructing a button:

    b1=Button(can,bg="black",image=bimage,command=location(0,0))

we should be careful to pass a function value as the 'command': if we use
parens prematurely, what ends up happening is that command gets set to the
return value of calling 'location(0, 0)'.


It looks we want to set 'command' to a function value that, when called,
does a 'location(0,0)'.  We can do that:

#######
def reset():
    location(0, 0)
b1 = Button(can,bg="black",image=bimage,command=reset)
#######

'reset' is a function that, when called, does location(0, 0).


Please feel free to ask more questions about this.  Good luck to you!



More information about the Tutor mailing list