pythonware.com products ::: library ::: search ::: daily Python-URL!
   

Validating Data

Back   Next   

 Validating Data

What if the user types bogus data into the dialog? In our current example, the apply method will raise an exception if the contents of an entry field is not an integer. We could of course handle this with a try/except and a standard message box:

    def apply(self):
        try:
            first = int(self.e1.get())
            second = int(self.e2.get())
            dosomething((first, second))
        except ValueError:
            tkMessageBox.showwarning(
                "Bad input",
                "Illegal values, please try again"
            )

There's a problem with this solution: the ok method has already removed the dialog from the screen when the apply method is called, and it will destroy it as soon as we return. This design is intentional; if we carry out some potentially lengthy processing in the apply method, it would be very confusing if the dialog wasn't removed before we finished. The Dialog class already contain hooks for another solution: a separate validate method which is called before the dialog is removed.

In the following example, we simply moved the code from apply to validate, and changed it to store the result in an instance attribute. This is then used in the apply method to carry out the work.

        def validate(self):
            try:
                first= int(self.e1.get())
                second = int(self.e2.get())
                self.result = first, second
                return 1
            except ValueError:
                tkMessageBox.showwarning(
                    "Bad input",
                    "Illegal values, please try again"
                )
                return 0
        
        def apply(self):
            dosomething(self.result)

Note that if we left the processing to the calling program (as shown above), we don't even have to implement the apply method.

Back   Next