Arguments for button command via Tkinter?

Mike Meyer mwm at mired.org
Mon Oct 31 17:45:02 CET 2005


"dakman at gmail.com" <dakman at gmail.com> writes:
> Recently, I have been needing to do this alot and I can never find a
> way around it, the main reason I want to do this is because for example
> in the application I am making right now, it creates a grid of buttons
> in a loop and they all have the same purpose so they need to call the
> same method, within this method they need to change the background
> color of the button clicked, I've tried stuff like...
>
> button['command'] = lambda: self.fill(button)
>
> def fill(self, wid):
>     button['bg'] = '#ff0000'
>
> But that's no good, everytime it I do click a button the lambda method
> I have setup keeps getting recreated so all of the button commands
> point to the same lambda method, I have also tried appending them to an
> array, and calling them from that.
>
> Anyone have any clue as of what to do? Thanks.

People have pointed out how to do this with a class, but you can do it
with lambdas as well. I suspect the problem you're having is that
python is binding values at call time instead of at definition time,
but it's hard to tell without more of your source code.

If I'm right, one solution is to make the values you want bound at
definition time optional arguments to the lambda, bound to the correct
value then. So you'd do:

      button['command'] = lambda b = button: self.fill(b)

The version you used will look up the name button when the lambda is
invoked. My version will look it up when the lambda is defined.

         <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list