main window in tkinter app

Christopher Subich spam.csubich+block at block.subich.spam.com
Wed Jul 20 09:01:50 CEST 2005


William Gill wrote:
> O.K. I tried from scratch, and the following snippet produces an 
> infinite loop saying:
> 
>   File "C:\Python24\lib\lib-tk\Tkinter.py", line 1647, in __getattr__
>       return getattr(self.tk, attr)
> 
> If I comment out the __init__ method, I get the titled window, and print 
> out self.var ('1')
> 
> 
> import  os
> from Tkinter import *
> 
> class MyApp(Tk):
>     var=1
>     def __init__(self):
>       pass
>     def getval(self):
>       return self.var
> 
> 
> app = MyApp()
> 
> app.title("An App")
> print app.getval()
> app.mainloop()

You're not calling the parent's __init__ inside your derived class.  I 
would point out where the Python Tutorial points out that you should do 
this, but it's not in the obvious place (Classes: Inheritance).

Python does -not- automagically call parent-class __init__s for derived 
classes, you must do that explicitly.  Changing the definition of your 
class to the following works:
 >>> class MyApp(Tk):
     var=1
     def __init__(self):
       Tk.__init__(self)
       pass
     def getval(self):
       return self.var

It works when you comment out __init__ because of a quirk in Python's 
name resolution.  As you'd logically expect, if you don't define a 
function in a derived class but call it (such as instance.method()), it 
will call the method from the base class.

You just proved that this works for __init__ methods also.  When you 
didn't define __init__ for your derived class, MyApp() called 
Tk.__init__(), which Does the Right Thing in terms of setting up all the 
specific Tkinter-specific members.



More information about the Python-list mailing list