passing data to Tkinter call backs

Nick Keighley nick_keighley_nospam at hotmail.com
Wed Jun 9 06:02:39 EDT 2010


On 9 June, 10:35, Bruno Desthuilliers <bruno.
42.desthuilli... at websiteburo.invalid> wrote:
> Nick Keighley a crit :

> > I'm trapping mouse clicks using
>
> > canvas.bind("<ButtonRelease-1>", mouse_clik_event)
>
> > def mouse_clik_event (event) :
> >      stuff
>
> > What mouse_clik_event does is modify some data and trigger a redraw.
> > Is there any way to pass data to the callback function? Some GUIs give
> > you a user-data field in the event, does Tkinter?
>
> Never used TkInter much, but if event is a regular Python object, you
> don't need any "user-data field" - just set whatever attribute you want, ie:
[...]
>  >>> class Event(object): pass
> ...
>  >>> e = Event()
>  >>> e.user_data = "here are my data"
>  >>> e.user_data
> 'here are my data'
>  >>>
>
> But I fail to see how this would solve your problem here - where would
> you set this attribute ???

Those other GUIs also give you a mechanism to pass the data. Say
another parameter in the bind call

> > Or am I reduced to using <spit> global data? A Singleton is just
> > Global Data by other means.
>
>  >>> from functools import partial
>  >>> data = dict()
>  >>> def handle_event(event, data):
> ...     data['foo'] = "bar"
> ...     print event
> ...
>  >>> p = partial(handle_event, data=data)

ah! the first time I read this I didn't get this. But in the mean time
cobbled something together using lambda. Is "partial" doing the same
thing but a little more elegantly?

>  >>> p(e)
> <__main__.Event object at 0xb75383ec>
>  >>> data
> {'foo': 'bar'}
>  >>>
>
> Note that data doesn't have to be global here.

# callback for mouse click event
def mouse_clik_event (event, data) :
    dosomething (event.x, event.y, data)
    draw_stuff (display, data)

data = Data(6.0, 0.2, 0.3)
draw_stuff (display, data)

# snag mouse
display.canvas.bind("<ButtonRelease-1>", lambda event:
mouse_clik_event (event, mandelbrot))




--
There are known knowns; there are things we know we know.
We also know there are known unknowns; that is to say we
know there are some things we do not know. But there are
also unknown unknowns -- the ones we don't know we don't
know.










More information about the Python-list mailing list