Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Science 112 Fundamentals of Programming II Data Fields for I/O and Message Boxes for Error Recovery.

Similar presentations


Presentation on theme: "Computer Science 112 Fundamentals of Programming II Data Fields for I/O and Message Boxes for Error Recovery."— Presentation transcript:

1 Computer Science 112 Fundamentals of Programming II Data Fields for I/O and Message Boxes for Error Recovery

2 A Mythical Tax Code All incomes are taxed at a single flat rate, say, 15% Each family member receives an exemption amount, say, $3500 tax = max(0.0, (income - exemptions * 3500) * 0.15) Inputs: income and number of exemptions Output: tax

3 TUI and Code print("Tax Calculator\n") RATE =.15 EXEMPTION_AMOUNT = 3500.0 income = float(input("Please enter your income: $")) exemptions = int(input("Please enter the number of exemptions: ")) tax = max(0.0, (income - exemptions * EXEMPTION_AMOUNT) * RATE) print("Your total tax is $%0.2f" % tax)

4 TUI and GUI

5 Data Fields The IntegerField class is used for the I/O of integers only The FloatField class is used for the I/O of integers or floats Use addIntegerField and addFloatField, respectively

6 Attributes and Methods Field attributes –value (the field’s initial numeric value) –state (“normal” or “readonly”) –width (20 columns for float fields, 10 for integer fields) –precision (for float fields only, infinite by default) Field methods –getNumber() returns the field’s value as a number –setNumber(anIntOrFloat) resets the field’s value –setPrecision(anInt) for float fields only

7 class TaxCode(EasyFrame): """Application window for the tax calculator.""" RATE =.15 EXEMPTION_AMOUNT = 3500.0 def __init__(self): """Sets up the window and the widgets.""" EasyFrame.__init__(self, title = "Tax Calculator") # Label and field for the income self.addLabel(text = "Income", row = 0, column = 0) self.incomeField = self.addFloatField(value = 0.0, row = 0, column = 1) # Label and field for the number of exemptions self.addLabel(text = "Exemptions", row = 1, column = 0) self.exField = self.addIntegerField(value = 0, row = 1, column = 1)

8 class TaxCode(EasyFrame): """Application window for the tax calculator.""" RATE =.15 EXEMPTION_AMOUNT = 3500.0 def __init__(self): """Sets up the window and the widgets.""" EasyFrame.__init__(self, title = "Tax Calculator")... # The command button self.button = self.addButton(text = "Compute", row = 2, column = 0, columnspan = 2, command = self.computeTax) # Label and field for the tax self.addLabel(text = "Total tax", row = 3, column = 0) self.taxField = self.addFloatField(value = 0.0, row = 3, column = 1, precision = 2, state = "readonly")

9 class TaxCode(EasyFrame): """Application window for the tax calculator.""" RATE =.15 EXEMPTION_AMOUNT = 3500.0 def __init__(self): """Sets up the window and the widgets.""" EasyFrame.__init__(self, title = "Tax Calculator")... # The event handling method for the button def computeTax(self): """Obtains the data from the input fields and uses them to compute the tax, which is sent to the output field.""" income = self.incomeField.getNumber() exemptions = self.exField.getNumber() tax = max(0.0, (income - exemptions * TaxCode.EXEMPTION_AMOUNT) \ * TaxCode.RATE) self.taxField.setNumber(tax)

10 Input Errors: Number Out of Range

11 Error Recovery Check for inputs out of range Pop up a message box with a descriptive error message Continue to wait for new inputs

12 def computeTax(self): """Obtains the data from the input fields and uses them to compute the tax, which is sent to the output field. Responds with error message if inputs are invalid.""" income = self.incomeField.getNumber() exemptions = self.exField.getNumber() if income < 0 or exemptions < 0: self.messageBox("ERROR ALERT", "Income and number of exemptions must be >= 0") return tax = max(0.0, (income - exemptions * TaxCode.EXEMPTION_AMOUNT) \ * TaxCode.RATE) self.taxField.setNumber(tax)

13 Input Errors: Bad Digits

14 Trapping Exceptions Must use Python’s try / except statement When exception is trapped, pop up a message box with an error message try: except :

15 def computeTax(self): """Obtains the data from the input fields and uses them to compute the tax, which is sent to the output field. Responds with error message if inputs are invalid.""" try: income = self.incomeField.getNumber() exemptions = self.exField.getNumber() if income < 0 or exemptions < 0: self.messageBox("ERROR ALERT", "Income and number of exemptions must be >= 0") return tax = max(0.0, (income - exemptions * TaxCode.EXEMPTION_AMOUNT) \ * TaxCode.RATE) self.taxField.setNumber(tax) except ValueError: self.messageBox("ERROR ALERT", "Inputs must be numbers") Trapping an Exception

16 Widgets for Text I/O A text field (class TextField ) is used for the I/O of one-line strings A text area (class TextArea ) is used for the I/O of multiple lines of text See the breezypythongui site for details

17 Example: A Simple Text File Editor Shows a text area to view and edit the contents of a text file Includes command buttons for opening and saving a file

18 App Window at Startup

19 Pop up an Open File Dialog

20 Load File Contents into Text Area

21 from breezypythongui import EasyFrame import tkinter.filedialog class FileDialogDemo(EasyFrame): """Demonstrates file dialogs and a text area.""" def __init__(self): """Sets up the window and widgets.""" EasyFrame.__init__(self, "File Dialog Demo") self.outputArea = self.addTextArea("", row = 0, column = 0, columnspan = 2, width = 80, height = 15) self.addButton(text = "Open", row = 1, column = 0, command = self.openFile) self.addButton(text = "Save As...", row = 1, column = 1, command = self.saveFileAs)

22 from breezypythongui import EasyFrame import tkinter.filedialog class FileDialogDemo(EasyFrame): """Demonstrates file dialogs and a text area."""... # Event handling methods def openFile(self): """Pops up an open file dialog, and if a file is selected, displays its text in the text area.""" filetypes = [("Python files", "*.py"), ("Text files", "*.txt")] fileName = tkinter.filedialog.askopenfilename(parent = self, filetypes = filetypes) if fileName != "": file = open(fileName, "r") text = file.read() file.close() self.outputArea.setText(text) self.setTitle(fileName) def saveFileAs(self): """Pops up a save file dialog, and if a file is selected, saves the contents of the text area to the file.""" fileName = tkinter.filedialog.asksaveasfilename(parent = self) if fileName != "": text = self.outputArea.getText() file = open(fileName, "w") file.write(text) file.close() self.setTitle(fileName)

23 For Monday (actually, Tuesday) Graphics and Mouse Events


Download ppt "Computer Science 112 Fundamentals of Programming II Data Fields for I/O and Message Boxes for Error Recovery."

Similar presentations


Ads by Google