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()
        
def update_period(event):
    periodic_cb.period = event.new

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=False, button_type='primary')
periodic_toggle.param.watch(toggle_periodic_callback, 'value')

period = pn.widgets.Spinner(name="Period (ms)", value=500, step=50, start=50)
period.param.watch(update_period, 'value')

periodic_cb = static_text.add_periodic_callback(
    generate_random_number, period=period.value, start=False)  # period in milliseconds

col = pn.Column(generate_button, period, periodic_toggle, static_text)
col.servable()
In [ ]:
 

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