Tutorial Brief

Handling the wivents of widgets using:

  • on_click()
  • on_trait_change()

Video Tutorial: http://youtu.be/hXS4xhyx0a8


In [1]:
from IPython.html import widgets

widgets.on_click()


In [2]:
def print_msg(widget):
    print "You have clicked (%s)" % widget.description

container = widgets.ContainerWidget()

button_1 = widgets.ButtonWidget(description="Click Me")
button_2 = widgets.ButtonWidget(description="Don't Click Me")

button_1.on_click(print_msg)
button_2.on_click(print_msg)

container.children = [button_1, button_2]

container


You have clicked (Click Me)
You have clicked (Don't Click Me)

widget.on_trait_change()


In [3]:
container = widgets.ContainerWidget()

control_1 = widgets.FloatTextWidget(description="X: ")
control_2 = widgets.FloatTextWidget(description="Y: ")
control_3 = widgets.SelectWidget(description= "Operation", values=["+","-","*","/"])
control_4 = widgets.LatexWidget(value="Formula: NA")
control_5 = widgets.LatexWidget(value="Result: 0.0")

container.children = [control_1, control_2, control_3, control_4, control_5]

def calculate_form(name):
    # Retreive values from form
    form = container.children
    X = form[0].value
    Y = form[1].value
    operation = form[2].value
    
    # Build Fomula
    formula = str(X) + operation + str(Y)
    form[3].value = "Formula: %s" % formula
    
    # Check if Divive by Zero
    if Y == 0.0 and operation == "/":
        form[4].value = "Div by Zero"
    else:
        # Evaluate fumula
        form[4].value = str(eval(formula))
    print "%s = %s" % (formula, control_5.value)

# Add Handlers
control_1.on_trait_change(calculate_form, "value")
control_2.on_trait_change(calculate_form, "value")
control_3.on_trait_change(calculate_form, "value")

container


0.0-0.0 = 0.0
0.0*0.0 = 0.0
0.0/0.0 = Div by Zero
0.0/4.0 = 0.0
2.0/4.0 = 0.5
2.0+4.0 = 6.0

In [4]:
container


2.0/4.0 = 0.5
2.2/4.0 = 0.55
2.25/4.0 = 0.5625
2.254/4.0 = 0.5635
2.2547/4.0 = 0.563675
2.25478/4.0 = 0.563695
2.254785/4.0 = 0.56369625
2.2547854/4.0 = 0.56369635
2.25478546/4.0 = 0.563696365
2.254785465/4.0 = 0.56369636625
2.2547854658/4.0 = 0.56369636645
2.25478546587/4.0 = 0.563696366467
2.25478546588/4.0 = 0.56369636647
2.25478546588/4.0 = 0.56369636647
2.25478546588/4.0 = 0.56369636647
2.25478546588/4.0 = 0.56369636647
2.25478546588/4.4 = 0.512451242245
2.25478546588/4.45 = 0.506693363119
2.25478546588/4.458 = 0.505784088354
2.25478546588/4.4585 = 0.505727367025
2.25478546588/4.45854 = 0.505722829868
2.25478546588/4.458542 = 0.505722603012
2.25478546588/4.4585426 = 0.505722534956
2.25478546588/4.45854264 = 0.505722530419
2.25478546588/4.458542648 = 0.505722529511
2.25478546588/4.4585426481 = 0.5057225295