AttributeError when using validatecommand on a Spinbox
Question: I am doing a test writing a script that validate a spinbox to implement it on
a larger system, but I am struggling with python because it is warning that
there is no spinbox attribute on my `Window` class. Check my code:

    
    
    from Tkinter import *
    
    class Window:
    
      def __init__(self, toplevel):
    
        self.spinbox = Spinbox(toplevel, from_ = 0, to = 10,
                               validate = 'all', validatecommand = self.validate)
        self.spinbox.pack()
    
      def validate(self):
    
        print self.spinbox.get()
    
    root = Tk()
    Window(root)
    root.mainloop()
    

This is the error it is giving:

    
    
    Exception in Tkinter callback
    Traceback (most recent call last):
      File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
        return self.func(*args)
      File "D:\DOCS\FILIPE\PROGRAMMING\PYTHON\Tkinter sandbox\01 - spinbox validate.
    py", line 13, in validate
        print self.spinbox.get()
    AttributeError: Window instance has no attribute 'spinbox'
    

Anyone could help me with this one?


Answer: If you add some `print` statements to your code:

    
    
    class Window:
      def __init__(self, toplevel):
        print "A start", self, self.__dict__
        self.spinbox = Spinbox(toplevel, from_ = 0, to = 10,
                               validate = 'all', validatecommand = self.validate)
        self.spinbox.pack()
        print "A end", self, self.__dict__
    
      def validate(self):
        print "B", self, self.__dict__
        print self.spinbox.get()
    #...
    

You get the output:

    
    
    A start <__main__.Window instance at 0x7fe4f8deec20> {}
    B <__main__.Window instance at 0x7fe4f8deec20> {}
    Exception in Tkinter callback
    Traceback (most recent call last):
      File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1532, in __call__
        return self.func(*args)
      File "t.py", line 14, in validate
        print self.spinbox.get()
    AttributeError: Window instance has no attribute 'spinbox'
    A end <__main__.Window instance at 0x7fe4f8deec20> {'spinbox': <Tkinter.Spinbox instance at 0x7fe4f8e0da28>}
    

This means that the validate function is called inside the constructor to
validate the initial value, and at that point `self.spinbox` has not yet been
set. You will need to either check if you are still constructing or delay
setting `validatecommand` like this:

    
    
    self.spinbox = Spinbox(toplevel, from_ = 0, to = 10,
                           validate = 'all')
    self.spinbox["validatecommand"] = self.validate
    self.spinbox.pack()
    

