Changing global variables in tkinter/pmw callback

Alex Martelli aleaxit at yahoo.com
Wed Apr 11 05:35:58 EDT 2001


"Brian Elmegaard" <be at mek.dtu.dk> wrote in message
news:3AD41D9A.42361F21 at mek.dtu.dk...
>
> > Which would become, to be literal in the transliteration:
> >
> >     def configure_command(self=self, button=button,
> >             buttons=self.buttons, setting=CurrentCanvasSetting):
> >         self.apply(button, buttons, setting)
> >
> >     button.configure(command = configure_command)
>
> So that's the way. I see.

It's ONE way -- I, personally, tend to find it more
readable than lambda, but personal taste matters here.


> > Here, if I understand correctly, what you're trying to do
> > is somehow set an appropriate "global" string when a
> > function is executed.  If that CurrentCanvasSetting is
>
> yes.
> >
> >     def apply(self, button, modobj, varname):
> >         setattr(modobj, varname, button.cget('text'))
>
> Ahh. But still it's not really like assigning to a global...

Why not?  If modobj is the module object of the current
module, the semantics of setattr are EXACTLY identical
to (say variable varname's value is string 'foo'):
    global foo
    foo = button.cget('text')
or, for more general (and arbitrary) values of modobj,
    modobj.foo = button.cget('text')

So, it is EXACTLY "really like assigning to a global".

Are you troubled by using setattr's "function-call"
syntax sugar to effect this binding, rather than the
"assignment-statement" syntax sugar?  You COULD mimic
the setattr by dynamically building up an assignment
statement in a string then executing it...:

    statement = modobj+'.'+varname+'=button.cget("text")'
    exec statement

...but I don't see why anybody would prefer such
convoluted obfuscation to setattr's simplicity.


Alex






More information about the Python-list mailing list