[Tutor] trying to put Tkinter widget handlers in a module

Alan Gauld alan.gauld at btinternet.com
Mon Sep 29 11:50:28 CEST 2008


"John Fouhy" <john at fouhy.net> wrote

> To get around it, you need to supply your handlers with a reference 
> to
> the Frame object.  I guess you could try something like this:
>
> ### handlers.py ###
> def handleCheckButton(obj):
>    def handler():
>        obj.doNotSend = obj.var.get()
>        if obj.doNotSend:
>            print '\nChecked'
>        else:
>            print '\nNot checked'
>    return handler
>
> ### main code ###
> c = Checkbutton(
>            master,
>            text='Check if yes',
>            variable=self.var,
>            command=handlers.handleCheckButton(self)
>            )
> ###

There is a simpler way using lambdas:

### handlers module ###
def handler(obj):
     obj.doNotSend = obj.var.get()
     if obj.doNotSend:
          print '\nChecked'
     else:
         print '\nNot checked'

### main code ###
c = Checkbutton(
            master,
            text='Check if yes',
            variable=self.var,
            command=lambda : handlers.handler(self)
            )


> I think moving some of your class functionality out to another
> module could easily confuse people..

This is key. In general it is better to keep the handlers in the 
class.
However the handlers should be quite short. If they need to manipulate
data etc then that should be in a separate method/function which
should be in a separate module. Event handlers typically manipulate
GUI widgets. Adding data for display, extracting data from dialog 
fields,
greying/ungreying menu items and buttons etc. Any manipulation of
the data should be delegated to the model classes that represent the
core objects in the application. These models are the ones that
should exist in other modules.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list