[Tutor] trying to put Tkinter widget handlers in a module
John Fouhy
john at fouhy.net
Mon Sep 29 05:13:04 CEST 2008
2008/9/29 <dwbarne at earthlink.net>:
> I am writing a large Python/Tkinter/Pmw program. It has become so big that I would like to move some of the widget handlers to a module for import. The following small program illustrates:
>
> # --- begin code ---
[...]
> c = Checkbutton(
> master,
> text='Check if yes',
> variable=self.var,
> command=self.handlerCheckButton,
> )
[...]
> def handlerCheckButton(self):
> self.doNotSend=self.var.get()
> if self.doNotSend:
> print "\nChecked"
> else:
> print "\nNot checked"
>
> Is there no way to put handlers in a module and import them? Is 'self' getting in the way?
Short answer -- yes. Well, I guess so -- if you posted the error
message you're getting, I'd be able to say for sure. Essentially,
you're trying to take the event handlers out of the class, but this is
a problem because they refer to attributes of the class.
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)
)
###
I think this would work, though I have not checked it. Whether it is
a good idea, though, is another question. I think moving some of your
class functionality out to another module could easily confuse
people..
--
John.
More information about the Tutor
mailing list