Fwd: Re: newbie: binding args in callbacks

Martin Franklin mfranklin1 at gatwick.westerngeco.slb.com
Wed Jul 10 11:32:57 EDT 2002


	
Whoops I sent to OP only!


----------  Forwarded Message  ----------

Subject: Re: newbie: binding args in callbacks
Date: Wed, 10 Jul 2002 14:59:46 +0000
From: Martin Franklin <mfranklin1 at gatwick.westerngeco.slb.com>
To: "Edward K. Ream" <edream at tds.net>

On Wednesday 10 Jul 2002 1:54 pm, Edward K. Ream wrote:
> This question was asked a while back, and I don't see it in the FAQ or
> in the archives...
>
> I would like to create a set of Tkinter callbacks that vary only in the
> bindings of a single argument. For example,  I would like to do:
>
> for val in vals:
>   b = Tk.Button(...,command=self.myCallback(val))
>
> But this doesn't work: it executes callback, rather than returning the
> callback function with the second arg bound to val.
>
> I also tried:
>
> for val in vals:
>  callback=lambda None:self.myCallback(x=val)
>  b = Tk.Button(...,command=callback)
>
> But that doesn't quite work either.  When the callback executes I get:
> TypeError: <lambda>() takes exactly 1 argument (0 given)
>
> Can someone explain how to do this?  Thanks.

Create a callback class that uses the built in __call__ method



class Callback:
    def __init__(self, value):
        self.value=value



    def __call__(self):
        ## do somthing with self.value
        if callable(self.value):
            self.value()


## so the GUI build looks like
for val in vals:
    b = Tk.Button(...,command=self.Callback(val))
    b.pack...............

Example....


[bpse at m-franklin dev]$ python
Python 2.2.1 (#3, May 29 2002, 20:32:44)
[GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> from Tkinter import *
>>>
>>> root=Tk()
>>> class Callback:

...     def __init__(self, value):
...             self.value=value
...     def __call__(self):
...             try:
...                     self.value()
...             except:
...                     print 'Cannot call', self.value
...

>>> b=Button(root, text='Press ME!', command=Callback(1))
>>> b.pack()
>>> Cannot call 1

Cannot call 1
Cannot call 1


Cheers
Martin

> Edward
> --------------------------------------------------------------------
> Edward K. Ream   email:  edream at tds.net
> Leo: Literate Editor with Outlines
> Leo: http://personalpages.tds.net/~edream/front.html
> --------------------------------------------------------------------

-------------------------------------------------------

-- 
Martin Franklin
Initial Software Solutions
(44) (0)1293 556629 / (44) (0)1234 888960
mfranklin1 at gatwick.westerngeco.slb.com
Wed Jul 10 15:32:32 2002





More information about the Python-list mailing list