Random number generator

Download this notebook from GitHub (right-click to download).


In [ ]:
import panel as pn
import numpy as np
pn.extension()

This example creates a random number generator that periodically updates every two seconds, or with a click of a button.

This demonstrates how to add a periodic callback, how to link a button and a toggle to a couple callbacks--the former to manually generate a random number and the latter to toggle periodic generation of a random number.

In [ ]:
def generate_random_number(event=None):
    static_text.value = np.random.randint(low=100000, high=200000)

def toggle_periodic_callback(event):
    if event.new is True:
        periodic_cb.start()
    else:
        periodic_cb.stop()

static_text = pn.widgets.StaticText(name='Periodic Random Number Generator',
                                    value='000000')

generate_button = pn.widgets.Button(name='Generate New Number')
generate_button.on_click(generate_random_number)

periodic_toggle = pn.widgets.Toggle(name='Periodically Generate',
                                    value=True, button_type='primary')
periodic_toggle.param.watch(toggle_periodic_callback, 'value')

periodic_cb = static_text.add_periodic_callback(
    generate_random_number, period=2000)  # period in milliseconds

col = pn.Column(generate_button, periodic_toggle, static_text)
col.servable()

Download this notebook from GitHub (right-click to download).