-
Notifications
You must be signed in to change notification settings - Fork 2
Construction of a Simple Example
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.
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.
-
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('')
-
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.
TextField
s, 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)'
- retrieve the operand-fields' values.
-
Call that function whenever the operands' values change.
TextField
s, 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 onlhs
andrhs
: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.) -
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!
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()