error explanation - 'statInter' object has no attribute 'tk'
The problem is your derived StatInter
class (CamelCasing the class name as suggested in PEP 8 - Style Guide for Python Code) doesn't initialize its base classes, which generally doesn't happen implicitly in Python (as it does in say, C++).
In order to do that from within the StatInter.__init__()
method, you're going to need to know the parent
widget that will contain it (all widgets except the top level window are contained in a hierarchy) — so an extra argument needs to be passed to the derived class's constructor so it can be passed on to each of the base class constructors.
You haven't encountered another problem yet, but likely will soon. To avoid it, you're also going to have explicitly pass self
when explicitly calling the base class methods in button()
and field()
.
from tkinter import *window = Tk()window.title('Tea timer')window.minsize(300,100)window.resizable(0,0)class StatInter(Button, Entry): def __init__(self, parent, posx, posy): # Added parent argument Button.__init__(self, parent) # Explicit call to base class Entry.__init__(self, parent) # Explicit call to base class self.posx = posx # So the variables inside the class are defined broadly self.posy = posy def button(self): Button.grid(self, row=self.posx, column=self.posy) # Add self def field(self): Entry.config(self, width=5) # Add selfsth = StatInter(window, 1, 2) # Add parent argument to callsth.grid(row=1, column=2)window.mainloop()
The reason you get this error is because you never invoke either of the constructors from the classes you're inheriting from (either Button
or Entry
).
If you change your __init__
to be:
def __init__(self, posx, posy): Button.__init__(self) self.posx = posx # So the variables inside the class are defined broadly self.posy = posy
Then you won't get the error you were having previously, and a little window pops up. In the new __init__
, we explicitly invoke Button
's constructor.
Unlike Java and some other languages, the super
constructor is NOT invoked by default. I assume that each class inheriting from other tkinter
classes must have a tk
field. By invoking the parent constructor of your choice, this field will be created. If you don't invoke a parent constructor, though, then this will not be an established field, and you'll get the error you have described ('statInter' object has no attribute 'tk').
HTH!