StringVar followup question

Joshua Macy amused at webamused.com
Thu Mar 16 09:50:51 EST 2000


Gordon McMillan wrote:
> 
> Timothy Grant wrote:
> 
> > OK, now I'm really going to show my ignorance.
> >
> > In general, I have been writing my code like this:
> >
> > import mod1
> > import mod2
> >
> > class def1:
> >         self.a = StringVar()
> >         self.b = StringVar()
> 
> Is that for real, or just email-sloppiness? There is no "self" at
> class scope. Top level statements in a class (usually just
> method "def"s) are evaluated at parse time. Ignoring the "self",
> this would (1) mean that StringVar() was evaluated before a tk
> instance exists, and (2) make all instances of def1 refer to the
> same StringVars.
> 
> > class def2:
> >         self.x = StringVar()
> >         self.y = StringVar()
> >
> > if __name__ == '__main__':
> >         root = Tk()
> >         Pmw.initialise(root)
> >
> >         x = def1(root)
> >
> >         root.mainloop()
> >
> > I thought the above would would initialize my instance of Tk create an
> > instance of my base class and go.  However, it appears that Python is
> > generating its errors on parsing the class def1, which happens before I
> > actually initialize Tk and Pmw. What would be the correct way to
> > structure this thing?
> >
> > Thanks.
> >
> >
> > --
> > Stand Fast,
> >     tjg.
> >
> > Chief Technology Officer              tjg at exceptionalminds.com
> > Red Hat Certified Engineer            www.exceptionalminds.com
> > Avalon Technology Group, Inc.                   (503) 246-3630
> > >>>>>>>>>>>>Linux...Because rebooting isn't normal<<<<<<<<<<<<
> >
> > --
> > http://www.python.org/mailman/listinfo/python-list
> 
> - Gordon


  It appears to me that the other problem with the example code is that
it never imports Tkinter (or Pmw for that matter).  The following code
runs without complaint:

from Tkinter import *

class Test:  # personally, I prefer not to name classes things like
def1, which are easily mistaken for reserved words
    def __init__(self):
	self.a = StringVar()
	self.b = StringVar()

if __name__ == '__main__':
    root = Tk()
    x = Test()

Referring to StringVar before Tk is instantiated is okay, as long as
Tkinter has been imported already.  Trying to instantiate StringVar
objects does fail if no Tk object has been instantiated.  You can see
this by trying to do x = Test() before the root = Tk().  Apparently
StringVar does rely on a module level variable that gets created as part
of the initialization of Tk (from the exception, it looks like
"master").


  Joshua



More information about the Python-list mailing list