Message Boxes

A message box can be used to announce a significant event, such as a user input error.  One place where this might occur is when the program attempts to get a number from a numeric entry field.  If the userÕs input text cannot be converted to a number, the getNumber method raises a ValueError.  A robust application can respond with a standard try-except pattern, which pops up a message box and allows her to try again.  The next code segment shows the event handler from a circle area program (circlearea3.py) that recovers from both number format errors and invalid radius errors.

 

def computeArea(self):

    """Inputs the radius, computes the area,

    and outputs the area.  Responds to number format

    errors and to invalid data errors (input < 0) with

    message boxes."""

    try:

        radius = self.radiusField.getNumber()

        if radius < 0:

            self.messageBox(title = "ERROR",

                            message = "Radius must be >= 0.")

        else:

            area = radius ** 2 * math.pi

            self.areaField.setNumber(area)

    except ValueError:

            self.messageBox(title = "ERROR",

                            message = "Radius must be a number.")

 

 

Here is a screen shot of the programÕs main window and the message box resulting from an input error (an o was typed instead of a 0):