Skip to content

Construction of a Simple Example

speezepearson edited this page Nov 22, 2015 · 3 revisions

To illuminate how this package works, I'll think out loud as I construct a very simple GUI.

I want a GUI that will add two user-submitted numbers, and show the user the result. As the user changes the text-field values, the answer should update automatically, and if it can't parse the numbers, the result is replaced with an error message. It will look like this.

Concepts

On a high conceptual level: there are three pieces of this interface that do interesting things (the operand fields and the result), so the first thing I'll do is create those pieces. Then I'll write a function that parses the operand-field values and sets the result, and arrange for that function to get called whenever the operands change. Then I'll create a GUI with all the pieces laid out the way I want, and run the GUI.

Implementation

  1. Create the dynamic pieces of the interface. The operands are text fields, and the result is a piece of text. browsergui provides classes for both of those, fortunately:

    from browsergui import GUI, Text, TextField
    lhs = TextField()
    rhs = TextField()
    result = Text('')
  2. Write a function that parses the operand-fields' values and sets the result text.

    To do this, we need to:

    • retrieve the operand-fields' values. TextFields, like all other elements that allow the user to enter some input, have a .value property representing the current value.
    • add those values. Easy.
    • change the result text to the sum. Text instances have a .text property representing the contents, and we can set this property.

    Let's write a function to do this:

    def update_result():
      x = lhs.value
      y = rhs.value
      try:
        result.text = float(x) + float(y)
      except ValueError:
        result.text = '(parse error)'
  3. Call that function whenever the operands' values change.

    TextFields, like all other elements that allow the user to enter some input, have a .change_callback attribute, which should be a parameterless function to call whenever the value changes. All I have to do is set that attribute on lhs and rhs:

    lhs.change_callback = rhs.change_callback = update_result

    (We could instead decorate update_result with @lhs.def_change_callback and @rhs.def_change_callback for arguably-prettier code.)

  4. Create a GUI with all the pieces laid out the way I want, and run it.

    gui = GUI(lhs, Text(" + "), rhs, Text(" = ", result))
    gui.run()

Done!

Final Product

from browsergui import GUI, Text, TextField

lhs = TextField()
rhs = TextField()
result = Text('')

@lhs.def_change_callback
@rhs.def_change_callback
def update_result():
  x = lhs.value
  y = rhs.value
  try:
    result.text = float(x) + float(y)
  except ValueError:
    result.text = '(parse error)'

gui = GUI(lhs, Text(" + "), rhs, Text(" = "), result)
gui.run()
Clone this wiki locally