Tkinter command parameters
Gustavo Cordova
gcordova at hebmex.com
Mon May 20 09:40:47 EDT 2002
>
> When I try to pass an argument to a button's function, it executes the
> function
> upon loading rather than when the button is pressed. When the button
> is pressed nothing happens.
>
> the code is something like this:
>
> self.mybutton = Button(parent, command = func(1))
> self.mybutton.grid()
>
> def func(number):
> print str(number)
>
> What am I doing wrong?
>
Because, with ''' command = func(1) ''' you're assigning to "command"
the result of calling "func" with an argument "1"; consider the parenthesis
a "call" operation.
What you need is to set "command" to a reference of the function
you want called whenever the button is pressed. Also, if you want
to defer calling "func" with an argumento "1", you need to create
a function without arguments which will in turn call "func(1)".
You can do that with:
def _(): func(1)
self.mybutton = Button(parent, command = _)
(I'm using "_" as a throwaway function name)
Or, also with lambda:
self.mybutton = Button(parent, command = lambda : func(1))
-gustavo
More information about the Python-list
mailing list