passing data to Tkinter call backs

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Wed Jun 9 05:35:19 EDT 2010


Nick Keighley a écrit :
> Hi,
> 
> If this is the wrong place for Tkinter in python please direct me
> elsewhere!
> 
> 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:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> 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 ???

> 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)
 >>> p(e)
<__main__.Event object at 0xb75383ec>
 >>> data
{'foo': 'bar'}
 >>>

Note that data doesn't have to be global here.




More information about the Python-list mailing list