import panel as pn
import numpy as np
pn.extension(sizing_mode="stretch_width")
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 and how to link a button and a toggle to a couple callbacks. The button to manually generate a random number and the toggle to toggle periodic generation of a random number.
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()
periodic_toggle.name="STOP Periodic Generation"
else:
periodic_cb.stop()
periodic_toggle.name="START Periodic Generation"
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='START Periodic Generation',
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 = pn.state.add_periodic_callback(
generate_random_number, period=period.value, start=False)
col = pn.Column(generate_button, period, periodic_toggle, static_text)
col
Lets wrap it into nice template that can be served via panel serve random_number_generator.ipynb
pn.template.FastListTemplate(
site="Panel",
title="Random Number Generator",
main=[
"This example creates a **random number generator** that updates periodically or with the click of a button.\n\nThis demonstrates how to add a **periodic callback** and how to link a button and a toggle to a couple of callbacks.",
col,
], main_max_width="768px",
).servable();