Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Science 112 Fundamentals of Programming II GUIs II:

Similar presentations


Presentation on theme: "Computer Science 112 Fundamentals of Programming II GUIs II:"— Presentation transcript:

1 Computer Science 112 Fundamentals of Programming II GUIs II:
Organizing Widgets with Panels Data Fields for I/O Message Boxes for Error Recovery

2 One Background or Two?

3 Problems If all the widgets go directly in the window, they must have only one common background They’re all in the same grid, but we might want different subgrids for different groups of widgets in the same window

4 Solution: Use Panels A panel is a blank rectangular area within a window A panel is added to the window’s grid, like other widgets Other widgets, including other panels, are then added to the panel

5 class FrenchFlag(EasyFrame):
"""Displays the French flag in the window.""" def __init__(self): """Sets up the window and the panels.""" EasyFrame.__init__(self, title = "French Flag", width = 300, height = 200) self.addPanel(0, 0, background = "blue") self.addPanel(0, 1, background = "white") self.addPanel(0, 2, background = "red"))

6 In CounterGUI: def __init__(self, counter):
"""Sets up the window, label, and buttons.""" EasyFrame.__init__(self, title = "Counter", background = "lightblue") self.counter = counter self.label = self.addLabel(text = str(self.counter), row = 0, column = 0, sticky = "NSEW", columnspan = 3, buttonPanel = self.addPanel(1, 0, background = "pink") buttonPanel.addButton(text = "Decrement", command = self.decrement) buttonPanel.addButton(text = "Reset", row = 0, column = 1, command = self.reset) buttonPanel.addButton(text = "Increment", row = 0, column = 2, command = self.increment)

7 About Panels Each panel has its own grid, independent of the enclosing window or panel’s grid Any type of widget that can be placed in a window can be placed in a panel Panels can be nested to any depth

8 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

9 TUI and Code print("Tax Calculator\n") RATE = .15
EXEMPTION_AMOUNT = 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)

10 TUI vs GUI

11 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

12 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

13 class TaxCode(EasyFrame):
"""Application window for the tax calculator.""" RATE = .15 EXEMPTION_AMOUNT = 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,

14 class TaxCode(EasyFrame):
"""Application window for the tax calculator.""" RATE = .15 EXEMPTION_AMOUNT = 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")

15 class TaxCode(EasyFrame):
"""Application window for the tax calculator.""" RATE = .15 EXEMPTION_AMOUNT = 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)

16 Input Errors: Number Out of Range

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

18 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)

19 Input Errors: Bad Digits

20 Trapping Exceptions Must use Python’s try/except statement
When exception is trapped, pop up a message box with an error message try: <code that might raise an exception> except <exception type>: <recovery code>

21 Trapping an Exception 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")

22 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

23 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

24 App Window at Startup

25 Pop up an Open File Dialog

26 Load File Contents into Text Area

27 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)

28 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) text = self.outputArea.getText() file = open(fileName, "w") file.write(text)

29 Scrolling list boxes Popup dialogs
For Wednesday Scrolling list boxes Popup dialogs


Download ppt "Computer Science 112 Fundamentals of Programming II GUIs II:"

Similar presentations


Ads by Google