The Streamlit API
The Streamlit application program interface, hereafter referred to as the Streamlit API, is the bread and butter of what our formidable web framework has to offer the world. With several dozen native commands that cater to rendering text, tables, charts, input widgets, and multimedia widgets to enacting page layout, data management, state management, as well as a whole host of other utilities, it is a comprehensive library that one should acquaint themselves with before proceeding to developing an application.
Displaying Text
The first series of commands in the Streamlit API accommodate to perhaps the most primitive need of any web application, namely, that of displaying text in all of its variety. In this section, we will present the commands that allow you to display text, rich text, tables, dataframes, plots, markdown, and more.
Write
Streamlit can
display a variety of inputs including but not limited to text, dataframes, and plots using the
st.write(*args, unsafe_allow_html=False) command. In addition, this command has the following unique attributes:
You may pass multiple arguments, and all of them will be rendered.
It will render differently depending on the input.
The return value of the function is None; therefore, its place in the application cannot be reused.
Table A-1st.write parameters
Parameter | Description |
---|
*args(any ) | Can be used with the following inputs: • string: Renders text, LaTeX expressions, and emoji shortcodes • Data_frame: Displays a dataframe as a table • error: Displays a code exception • func: Displays information about the function • module: Displays information about the module • dict: Displays a dictionary as an interactive widget • mpl_fig: Renders a Matplotlib plot • altair: Renders an Altair plot • keras: Renders a Keras model • graphviz: Renders a Graphviz graph • plotly_fig: Renders a Plotly plot • bokeh_fig: Renders a Bokeh plot • sympy_expr: Displays a SymPy expression formatted as LaTeX • htmlable: displays_repr_html_( ) for the object if available • obj: Prints the string of an object |
Unsafe_allow_html(bool ) | By default, any HTML detected will be escaped and treated as text. This may be turned off by setting this argument to True, although this is not recommended as it may compromise the users’ security. |
Displaying text with st.write will be formatted as plain text:
Markdown format can be used too:
st.write('**_Hello_ world**')
Outputting:
Objects can be passed as arguments, such as dataframes:
st.write(pd.DataFrame({
'Column 1': [1, 2, 3, 4],
'Column 2': [5, 6, 7, 8],
}))
The resulting dataframe will be rendered into a nicely formatted table:
Several arguments can be passed in the same call and will be printed in order:
Different objects can be used like the following example with plain text and a dataframe:
st.write('Hello world', dataframe)
Charts, figures, and models, such as described in the command
parameters, can also be displayed directly using st.write:
import pandas as pd
import numpy as np
import altair as alt
dataframe = pd.DataFrame(
np.random.randn(200, 3),
columns=['x', 'y', 'z'])
plot = alt.Chart(dataframe).mark_circle().encode(
x='x', y='y', size='z', color='z', tooltip=['x', 'y', 'z'])
Using st.write is a simple, fast, and convenient way to display data, but more control over the visualization can be obtained using specific API commands. The following subsections will offer a more comprehensive set of tools to display and visualize all types of elements along with the available options to customize the look and feel of the output.
Text
Streamlit displays plain text using the
st.text(str) command.
Table A-2st.text parameters
Parameter | Description |
---|
body(str ) | The string to display. |
Formatted text can be displayed using the
st.text(body) command:
Note that the results are equivalent to the st.write text when inputted as pure text.
Markdown
Streamlit can display strings formatted as markdown using the
st.markdown(body,unsafe_allow_html=False) command.
Table A-3st.markdown parameters
Parameter | Description |
---|
body(str ) | • Can be used to display string as GitHub-style markdown. For additional information, refer to https://github.github.com/gfm. • Can also be used with emoji shortcodes. For additional information on all supported shortcodes, refer to https://raw.githubusercontent.com/omnidan/node-emoji/master/lib/emoji.json. • Can also be used with LaTeX expressions by wrapping them in $ or $$. For additional information, refer to https://katex.org/docs/supported.html. |
unsafe_allow_html(bool ) | By default, any HTML detected will be escaped and treated as text. This may be turned off by setting this argument to True, although this is not recommended as it may compromise the users’ security. |
Streamlit can display markdown formatted text and easily combine it with LaTeX and emojis:
st.markdown('$overline{ANA}$, **_really_ likes** :doughnut:')
As expected, the results are the same that would be obtained using st.write with markdown text:
Markdown is an easy-to-read and easy-to-write plain text format that gives you the ability to render rich text with formatting that would have otherwise not been possible with normal text. Specifically, it allows you to write bold, italic, hyperlinked, and strike-through text with varying sizes. In addition, markdown permits writing tables, displaying images, and creating bulleted and numbered lists, as well as quotes, code, and checkboxes. For further information, please refer to
https://guides.github.com/features/mastering-markdown/. An example of each is shown as follows:
st.markdown(
"'
# Hello world
## Hello world
### Hello world
#### Hello world
##### Hello world
###### Hello world
"'
)
st.markdown('**Hello world**')
st.markdown('_Hello world_')
st.markdown('˜˜Hello world˜˜')
st.markdown(
"'
- Hello world
- Hello world
- Hello world
"'
)
st.markdown(
"'
1. Hello world
2. Hello world
3. Hello world
"'
)
st.markdown(
"'
- [x] Hello world
- [ ] Hello world
"'
)
st.markdown(
"'
"'
del' hello_world():
print('Hello world')
"'
"'
)
st.markdown(
"'
"'python
del' hello_world():
print('Hello world')
"'
"'
)
st.markdown('Check out [Streamlit](https://streamlit.io/)')
st.markdown('> Hello world')
st.markdown('![Image](https://avatars.githubusercontent.com/u/31454258?v=4)')
st.markdown(
"'
Name | Score 1 | Score 2
------------ | ------------- | -------------
Jessica | 77 | 76
John | 56 | 97
Alex | 87 | 82
"'
)
Title, Header, and Subheader
Typography in Streamlit can be managed using a three-level hierarchy of title, header, and subheader. The commands follow the same naming and accept the same parameterization: st.title(body, anchor=None), st.header(body, anchor=None), and st.subheader(body, anchor=None).
Table A-4st.title, st.header, and st.subheader parameters
Parameter | Description |
---|
body(str ) | The string to display. |
anchor(str ) | The anchor name of the title/header/subheader that can be accessed with #anchor in the URL. If the anchor is not invoked, Streamlit will automatically generate an anchor using the body text. |
The format used by Streamlit for the three hierarchical typographies is as follows:
st.title('Title')
st.header('Header')
st.subheader('Subheader')
Caption
Streamlit displays captions with small text using the
st.caption(str) command.
Table A-5st.caption parameters
Parameter | Description |
---|
body(str ) | The string to display. |
Smaller text can be displayed using the caption API for those cases where subheadings or alternative titles are needed:
st.title('Title')
st.header('Header')
st.subheader('Subheader')
st.text('Text')
st.caption('Caption')
Code
Streamlit renders code with syntax highlighting using the st.code(body, language=’python’) command.
Table A-6st.code parameters
Parameter | Description |
---|
body(str ) | The string to display as code. |
language(str ) | The programming language that the code is written in (used for rendering and syntax highlighting). If the language is not set, the code will be left without styling. |
The following example displays a block of Python code:
code = "'def hello_world(input):
print(input)"'
st.code(code, language='python')
LaTeX
Streamlit can display mathematical functions formatted as LaTeX using the
st.latex(body) command.
Table A-7st.latex parameters
Parameter | Description |
---|
body(str or SymPy expression) | The string and/or SymPy expression to display. For additional information on supported LaTeX functions, refer to https://katex.org/docs/supported.html. |
LaTeX can be useful, for instance, for displaying mathematical formulas:
st.latex(r"'
x = frac{{ - b pm sqrt {bˆ2 - 4ac} }}{{2a}}
"')
Magic Commands
Magic commands are characterized by Streamlit as functions that enable the developer to render markdown and data to applications in a very concise and easy manner. Whenever Streamlit detects a variable or literal value independently on its own line, it will automatically write that variable to the application using the st.write function. In addition, magic commands will ignore docstrings that are located at the beginning of scripts and functions.
Writing text directly without calling any of the Streamlit predefined functions by using the magic command is shown as follows:
Rendering a dataframe:
df = pd.DataFrame({'col1': [1,2,3]})
df # <-- Draw the dataframe
Writing the value of a variable:
x = 10
'x', x # <-- Draw the string 'x' and then the value of x
If required, you may turn off magic commands by modifying the “/
˜.streamlit/config.toml” file with the following
setting:
[runner]
magicEnabled = false
Displaying Data
Rendering data in all of its variety comes seamlessly with Streamlit. Using a host of native commands, you may display Pandas dataframes, tables, JSON documents, metrics, lists, and other miscellaneous data types.
Dataframes
Dataframes are displayed by Streamlit formatted as an interactive table using the
st.dataframe(data=None, width=None, height=None) command.
Table A-8st.dataframe parameters
Parameter | Description |
---|
data(pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, Iterable, dict, or None) | The data to be displayed: • Pandas.Styler: The pandas styling will be used on the dataframe, including most common cell values and colors. Enhanced features such as hovering, captions, or charts are currently not supported. Support for Styler is experimental. • PyArrow tables: PyArrow tables must be enabled by setting config.dataFrameSerialization = ”arrow”. PyArrow tables are not supported by default by Streamlit’s legacy dataframe serialization (i.e., with config.dataFrameSerialization = ”legacy”). |
width(int or None) | Width of the UI element in pixels. The default None value will set the width to the one of the page where it is being used. |
height(int or None) | If the height is set to None, it will equal the height of the page on which it is being used. |
The following example displays a dataframe using a heatmap that colors the intensity of the values as compared to other values, using a predefined Matplotlib
green colormap and a fixed width of 1000 pixels:
df = pd.DataFrame(
np.random.randn(10, 5),
columns=('col %d' % i for i in range(5)))
st.dataframe(df.style.background_gradient(), width=1000)
Tables
Static
tables are displayed with the
st.table(data=None) command.
Table A-9st.table parameters
Parameter | Description |
---|
data(pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, Iterable, dict, or None) | The table data. PyArrow tables must be enabled by settingconfig.dataFrameSerialization = ”arrow”. PyArrow tables are not supported by default by Streamlit’s legacy dataframe serialization (i.e., with config.dataFrameSerialization = “legacy”). |
Following the dataframe example, static tables are displayed in the same manner:
df = pd.DataFrame(
np.random.randn(10, 5),
columns=('col %d' % i for i in range(5)))
JSON
An interactive representation of a JSON file can be displayed in Streamlit using the st.json(body) command.
Table A-10st.json parameters
Parameter | Description |
---|
body(Object or str ) | The object to be printed as a JSON. The object or string referenced must be serializable to JSON. |
expanded(bool ) | Setting this parameter to True will set the initial state of the JSON element to expanded. By default, it is True. |
The following example shows a simple representation of a JSON object. The interactive visualization of Streamlit allows folding and unfolding of the branches.
st.json({
'A': 'a',
'B': 'b',
'C': [
'ca',
'cb',
'cc',
'cd',
],
'D': 'd',
})
Metric
The
st.metric(label, value, delta=None, delta_color=’normal’) command
displays in large and bold fonts a metric, indicator, or variable in a dashboard style. An optional change of status indicator can be added.
Table A-11st.metric parameters
Parameter | Description |
---|
label(str ) | The title for the metric. |
value(int, str, or None) | Value given to the metric. None is rendered as a long dash. |
delta(int, str, or None) | Small subindicator below the main one showing the change with regard to the last status. For negative numbers (int or float), or strings starting with a minus sign, the arrow will be rendered in red and pointing down; all other options will show in green and the arrow pointing up. If the delta is set to None (the default option), this subindicator will not be presented. |
delta_color(str) | This attribute inverses the color and the arrow by default for positive and negative values. It is intended for those cases where a negative change might be considered good, and vice versa. If set to “off,” the delta will be shown in gray for all cases. |
The following example shows a metric indicator of temperature without its delta. The indicator is then adjusted with the delta option to reflect the change from the previous value.
st.metric('Temperature', '26.7 C', '2.7 C')
Displaying Charts
Another area that Streamlit excels in is in visualizing data. Whether it is rendering a chart using their native command or displaying a third-party chart from Matplotlib, Altair, Vega-Lite, Plotly, Bokeh, PyDeck, or Graphviz, Streamlit allows you to integrate visualizations effortlessly.
Line, Area, and Bar Charts
Simple line, area, and bar charts can be rendered using the st.line_chart, st.area_chart, and st.bar_chart commands. To display a chart, you may use the following command: st.line_chart/st.area_chart/st.bar_chart(data, width, height, use_container_width).
Table A-12st.line_chart, st.area_chart, and st.bar_chart parameters
Parameter | Description |
---|
data(pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, Iterable, dict or None) | The data to be plotted. Streamlit’s legacy dataframe serialization does not include support for PyArrow tables (i.e., config.dataFrameSerialization = ‘legacy’). To utilize PyArrow tables, change the config setting to config.dataFrameSerialization = ‘arrow’. |
width(int ) | The chart’s width dimensions in pixels. If zero, the width is determined automatically. |
height(int ) | The chart’s height dimensions in pixels. If zero, the width is determined automatically. |
use_container_width(bool ) | When True, the chart width will adjust to the column width. This argument has precedence over the width argument. |
The following example shows the use of the three graphing options stacked and limited in height:
chart_data = pd.DataFrame(
np.random.randn(10, 2),
columns=['Value 1', 'Value 2'])
st.line_chart(chart_data, height=125)
st.area_chart(chart_data, height=125)
st.bar_chart(chart_data, height=125)
Pyplot
A Matplotlib
chart can be rendered using the following command:
st.pyplot(fig, clear_ figure, **kwargs).
Table A-13st.pyplot parameters
Parameter | Description |
---|
fig(Matplotlib Figure) | Figure to be plotted. |
clear_figure(bool ) | The figure will be cleared after being rendered when True. The figure will not be cleared after being rendered when False. When left unspecified, we pick a default based on the value of fig: • If fig is set, it defaults to False. • If fig is not set, it defaults to True. Similar to the Jupyter’s approach to Matplotlib rendering. |
**kwargs(any) | Matplotlib’s savefig function arguments. |
The following example shows how to display a Matplotlib bar chart in Streamlit:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randn(10, 3)
fig, ax = plt.subplots()
ax.hist(data, bins=10)
Altair
An Altair
chart can be displayed using the following command:
st.altair_chart(altair_chart, use_container_width).
Table A-14st.altair_chart parameters
Parameter | Description |
---|
altair_chart(altair.vegalite.v2.api.Chart ) | Altair figure object to render. |
use_container_width(bool ) | If this argument is set to True, the chart width will be set to the column width. |
The following example shows how to display an Altair scatter plot in Streamlit:
import pandas as pd
import numpy as np
import altair as alt
df = pd.DataFrame(np.random.randn(30, 3), columns=['Col1','Col2','Col3'])
fig = alt.Chart(df).mark_circle().encode(
x='Col1', y='Col2', size='Col3',
color='Col3',
tooltip=['Col1', 'Col2', 'Col3']
)
st.altair_chart(fig)
Vega-Lite
A Vega-Lite
chart can be displayed using the following command:
st.vega_lite_chart(data, spec, use_container_width, **kwargs).
Table A-15st.vega_lite_chart parameters
Parameter | Description |
---|
data(pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, Iterable, dict or None) | The data to be plotted. Streamlit’s legacy dataframe serialization does not include support for pyarrow tables (i.e., config.dataFrameSerialization = ‘legacy’). To utilize PyArrow tables, change the config setting toconfig.dataFrameSerialization = ‘arrow’. |
spec(dict or None) | The specification for the Vega-Lite chart. If the argument has already been set previously, this must be set to None. Please refer to https://vega.github.io/vega-lite/docs/ for additional information. |
use_container_width(bool ) | When True, the chart width will adjust to the column width. This argument has precedence over the Vega-Lite native argument. |
**kwargs(any) | Keyword version of spec parameter. |
The following example shows how to display a Vega-Lite scatter plot in Streamlit:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(30, 3), columns=['Col1','Col2','Col3'])
st.vega_lite_chart(df, {
'mark': {'type': 'circle', 'tooltip': True},
'encoding': {
'x': {'field': 'Col1', 'type': 'quantitative'},
'y': {'field': 'Col2', 'type': 'quantitative'},
'size': {'field': 'Col3', 'type': 'quantitative'},
'color': {'field': 'Col3', 'type': 'quantitative'},
},
}, width=500, height=400)
Plotly
A Plotly
chart can be displayed using the command
st.plotly_chart(figure_or_data, use_container_width, sharing, **kwargs).
Table A-16st.plotly_chart parameters
Parameter | Description |
---|
figure_or_data(plotly.graph_objs.Figure, plotly.graph_objs.Data) | The Plotly figure object to be rendered. For further information regarding Plotly Python charts, please refer to https://plot.ly/python/. |
use_container_width(bool ) | If this argument is set to True, the chart width will be set to the column width. |
sharing({‘streamlit’, ‘private’, ‘secret’, ‘public’} ) | This argument will specify the mode of rendering. If it is set to “streamlit,” the chart will be displayed in Plotly’s offline mode. Other modes will require access to a Plotly chart studio account; for further information, please refer to https://plotly.com/chart-studio/. |
**kwargs(null ) | Any argument that is accepted by Plotly’s plot() function may be provided here. |
The following example shows how to display a Plotly radar plot in Streamlit:
import pandas as pd
import numpy as np
import plotly.express as px
df = pd.DataFrame(np.random.randn(360, 1), columns=['Col1'])
fig = px.line_polar(df, r=df['Col1'], theta=df.index, line_close=True)
st.plotly_chart(fig)
Bokeh
A Bokeh
chart can be displayed using the command
st.bokeh_chart(figure, use_container_width).
Table A-17st.bokeh_chart parameters
Parameter | Description |
---|
figure(bokeh.plotting.figure.Figure) | The Bokeh figure object to be rendered. |
use_container_width(bool ) | If this argument is set to True, the chart width will be set to the column width. |
The following example shows how to display a Bokeh line chart in Streamlit:
import pandas as pd
import numpy as np
from bokeh.plotting import figure
df = pd.DataFrame(np.random.randn(10, 1), columns=['Col1'])
fig = figure(
x_axis_label='Index',
y_axis_label='Col1')
fig.line(df.index, df['Col1'], legend_label='Trend', line_width=2)
PyDeck
A PyDeck geospatial
map can be displayed using the command
st.pydeck_chart(pydeck_obj, use_container_width).
Table A-18st.pydeck_chart parameters
Parameter | Description |
---|
spec(pydeck.Deck or None) | The PyDeck figure object to be rendered. |
The following example shows how to display a PyDeck geospatial map in Streamlit:
import pandas as pd
import numpy as np
import pydeck as pdk
df = pd.DataFrame(
np.random.randn(100, 2)/[50, 50] + [29.76, -95.37],
columns=['latitude', 'longitude'])
st.pydeck_chart(pdk.Deck(
map_style='mapbox://styles/mapbox/light-v9',
initial_view_state=pdk.ViewState(
latitude=29.76,
longitude=-95.37,
zoom=12,
pitch=40,
),
layers=[
pdk.Layer(
'HexagonLayer',
data=df,
get_position='[longitude, latitude]',
radius=200,
elevation_scale=2,
elevation_range=[0, 500],
pickable=True,
extruded=True,
),
],
))
Graphviz
A Graphviz
chart can be rendered using the command
st.graphviz_chart(figure_or_dot, use_container_width).
Table A-19st.graphviz_chart parameters
Parameter | Description |
---|
figure_or_dot(graphviz.dot.Graph, graphviz.dot.Digraph, str ) | The Graphviz figure object to be rendered. |
use_container_width(bool ) | If this argument is set to True, the chart width will be set to the column width. |
The following example shows how to display a Graphviz graph in Streamlit:
import graphviz as graphviz
st.graphviz_chart("'
digraph {
A -> {B C} [style=dotted, shape=box]
B -> C
D -> F
F -> E
E -> A
B -> D
subgraph {
rank = same; A; B; C [shape=box];
A -> E [color=blue, style=dotted]
}
}
"')
Maps
A
Streamlit geospatial map can be displayed using the command
st.map(data, zoom, use_container_width).
Table A-20st.map parameters
Parameter | Description |
---|
data(pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict ) | The latitude and longitude of the points to be rendered on the map. |
zoom(int ) | The level of zoom when the map is first rendered. For further information, please refer to https://wiki.openstreetmap.org/wiki/Zoom_levels. |
The following example shows how to display a geospatial map in Streamlit:
import pandas as pd
import numpy as np
df = pd.DataFrame(
np.random.randn(100, 2)/[50, 50] + [29.76, -95.37],
columns=['latitude', 'longitude'])
Input Widgets
Streamlit offers a rich and diverse set of input widgets that enable the developer to cater to a wide variety of use cases. From simple buttons, sliders, and forms to color selectors, file uploaders, and select boxes, Streamlit possesses the entire spectrum of inputs.
Buttons
General-purpose
buttons can be created for any requirement with the command
st.button(label, key, help, on_click, args, kwargs, disabled=False) ➤ bool.
Table A-21st.button parameters
Parameter | Description |
---|
label(str ) | Label to be displayed in the button. |
key(str or int ) | Unique key, string or integer, to reference the button in the code. The parameter is optional and will be automatically generated if not provided. |
help(str ) | Tooltip to be displayed when the cursor is hovered over the widget. |
on_click(callable) | Callback function called when the button is clicked. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict ) | Dictionary of keyword arguments to pass to the callback. |
disabled(bool ) | Boolean argument used to disable the widget. |
The following example displays the results of a simple arithmetic calculation when the button is clicked:
def addition(a,b):
result = a + b
return result
if st.button('Not very useful button', key='b1'):
st.text('Not very useful button clicked')
st.write(addition(1,2))
Download Button
Download buttons can be added to our websites with the following command:
st.download_button(label, data, file_name, mime, key, help, on_click, args, kwargs, disabled=False) ➤ bool.
Table A-22st.download_button parameters
Parameter | Description |
---|
label(str ) | Label explaining the use of the button. |
data(str or bytes or file) | The contents of the file to download. Use caching to avoid recomputing on every rerun. |
file_name(str ) | Name of the file to be downloaded. If not specified, a name will be created automatically. |
mime(str or None) | The data MIME type. The default is “text/plain” for text files or “application/octet-stream” for binary files. |
key(str or int ) | Unique key, string or integer, to reference the button in the code. The parameter is optional and will be automatically generated if not provided. |
help(str ) | Tooltip to be displayed when the cursor is hovered over the widget. |
on_click(callable) | Callback function called when the button is clicked. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict ) | Dictionary of keyword arguments to pass to the callback. |
disabled(bool ) | Boolean argument used to disable the widget. |
The following example
displays how a Pandas dataframe can be downloaded as a CSV file using a download button:
data = pd.DataFrame({'a':[1,2,3],'b':[4,5,6]}).to_csv().encode('utf-8')
st.download_button(
label='Download CSV', data=data, file_name='data.csv', mime='text/csv')
Checkbox
A
checkbox can be added to our websites with the following command:
st.checkbox(label, value, key, help, on_change, args, kwargs, disabled=False) ➤ bool.
Table A-23st.checkbox parameters
Parameter | Description |
---|
label(str ) | Label of the checkbox. |
value(bool ) | Chose whether the checkbox is preselected by default when first rendered. Internally, this will be cast to bool. |
key(str or int ) | Unique key, string or integer, to reference the button in the code. The parameter is optional and will be automatically generated if not provided. |
help(str ) | Tooltip to be displayed when the cursor is hovered over the widget. |
on_change(callable) | Callback function invoked when the widget’s value changes. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict ) | Dictionary of keyword arguments to pass to the callback. |
disabled(bool ) | Boolean argument used to disable the widget. |
The checked and unchecked behavior of a checkbox widget is shown as
follows:
choice = st.checkbox('Healthy choice')
if choice:
st.write(':broccoli:')
else:
st.write(':doughnut:')
Radio Button
A
radio button can be added to our websites using the following command:
st.radio(label, options, index, format_func=special_internal_function, key, help, on_change, args, kwargs, disabled=False) ➤ any.
Table A-24st.radio parameters
Parameter | Description |
---|
label(str ) | Label of the radio group. |
options(Sequence, numpy.ndarray, pandas.Series, pandas.DataFrame, or pandas.Index) | Radio option labels. It will automatically cast to str. When using pandas.DataFrame, the first column will be selected as a source. |
index(int ) | Preselected option index on first render. |
format_func(function) | Auxiliary function used to modify the radio option labels. The str values for the labels are passed as arguments, and it returns a modified str as per the function logic. This option is purely cosmetic and has no impact in the operation or return values of the radio widget. |
key(str or int ) | Unique key, string or integer, to reference the button in the code. The parameter is optional and will be automatically generated if not provided. |
help(str ) | Tooltip to be displayed when the cursor is hovered over the widget. |
on_change(callable) | Callback function invoked when the widget’s value changes. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict ) | Dictionary of keyword arguments to pass to the callback. |
disabled(bool ) | Boolean argument used to disable the widget. |
The following example displays a two-option radio button and displays the
selection:
sport_selection = st.radio("What's the best football club in the World",
('Real Madrid', 'Other team'))
if sport_selection == 'Real Madrid':
st.write('That was easy :soccer:.')
else:
st.write('You are clearly wrong.')
Select Box
A
select box widget can be added to our websites using the following command:
st.selectbox(label, options, index, format_func=special_internal_function, key, help, on_change, args=None, kwargs, disabled=False) ➤ any.
Table A-25st.selectbox parameters
Parameter | Description |
---|
label(str ) | Label of the widget. |
options(Sequence, numpy.ndarray, pandas.Series, pandas.DataFrame, or pandas.Index) | Select option labels. It will automatically cast to str. When using pandas.DataFrame, the first column will be selected as a source. |
index(int ) | Preselected option index on first render. |
format_func(function) | Auxiliary function used to modify the option selection labels. The str values for the labels are passed as arguments, and it returns a modified str as per the function logic. This option is purely cosmetic and has no impact in the operation or return values of the widget. |
key(str or int ) | Unique key, string or integer, to reference the button in the code. The parameter is optional and will be automatically generated if not provided. |
help(str ) | Tooltip to be displayed when the cursor is hovered over the widget. |
on_change(callable) | Callback function invoked when the widget’s value changes. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict ) | Dictionary of keyword arguments to pass to the callback. |
disabled(bool ) | Boolean argument used to disable the widget. |
The following example displays a select box widget with two options:
option = st.selectbox('What would you like to watch?', ('Cricket', 'Baseball'))
st.write('You selected: **%s**' % option)
Multiselect Box
A multiple selection
widget can be added to our websites with the following command:
st.multiselect(label, options, default=None, format_func=special_internal_function,
key=None, help=None, on_change=None, args=None, kwargs=None, disabled=False) ➤ str.
Table A-26st.multiselect parameters
Parameter | Description |
---|
label(str ) | Label of the multiselect widget. |
options(Sequence, numpy.ndarray, pandas.Series, pandas.DataFrame, or pandas.Index) | Select option labels. It will automatically cast to str. When using pandas.DataFrame, the first column will be selected as a source. |
index(int ) | Preselected option index on first render. |
default([str] or None) | Default values. |
format_func(function) | Auxiliary function used to modify the selection labels. The str values for the labels are passed as arguments, and it returns a modified str as per the function logic. This option is purely cosmetic and has no impact in the operation or return values of the widget. |
key(str or int ) | Unique key, string or integer, to reference the button in the code. The parameter is optional and will be automatically generated if not provided. |
help(str ) | Tooltip to be displayed when the cursor is hovered over the widget. |
on_change(callable) | Callback function invoked when the widget’s value changes. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict ) | Dictionary of keyword arguments to pass to the callback. |
disabled(bool ) | Boolean argument used to disable the widget. |
The following example shows a multiselect widget with available four
options:
options = st.multiselect('What are your favorite seasons?',
['Spring', 'Summer', 'Autumn', 'Winter'])
st.write('You selected: %s' % ', '.join(options))
Slider
A
slider can be added to our websites using the following command:
st.slider(label, min_value, max_value, value, step, format, key, help, on_change, args, kwargs, disabled=False) ➤ value.
Table A-27st.slider parameters
Parameter | Description |
---|
label(str ) | Label explaining the use of the slider. |
min_value(a supported type or None) | The minimum allowed value. It defaults to 0 or 0.0 for int and floats, value – timedelta(days=14) for date/date-time values, time.min if a time. |
max_value(a supported type or None) | The maximum allowed value. Defaults to 100 or 1.0 for int and float, value + timedelta(days=14) for date/date-time values, time.max if a time. |
value(a supported type or a tuple/list of supported types or None) | The default value to be used when the widget is first rendered. To use a predefined range, a tuple/list should be passed as an argument with the min and max values. Defaults to min_value. |
step(int/float/timedelta or None) | The stepping interval. By default, set to 1 and 0.01 for int and float, timedelta(days=1) for date/datetime values, timedelta(minutes=15) if a time (or if max_value – min_value < 1 day). |
format(str or None) | A custom format string that specifies how the interface should render numbers in a printf-style format. The return value is not affected by the conversion. %d, %e, %f, %g, and %i are supported for formatting int/float values. For date/time/datetime formatting, use Moment.js syntax: https://momentjs.com/docs/#/displaying/format/. |
key(str or int ) | Unique key, string or integer, to reference the button in the code. The parameter is optional and will be automatically generated if not provided. |
help(str ) | Tooltip to be displayed when the cursor is hovered over the widget. |
on_change(callable) | Callback function invoked when the widget’s value changes. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict ) | Dictionary of keyword arguments to pass to the callback. |
disabled(bool ) | Boolean argument used to disable the widget. |
The following code implements a slider to select a time between 9.00 and 16.00
hours:
from datetime import time
meeting_time = st.slider('Select time:', value = time(11,00),
max_value = time(16,00), min_value = (time(9, 00)), format='hh:mm')
st.write('You are scheduled for: **%s**' % meeting_time)
Select Slider
A select slider
widget can be added to our websites using the following command:
st.select_slider(label, options, value, format_func, key, help, on_change, args, kwargs) ➤ value.
Table A-28st.select_slider parameters
Parameter | Description |
---|
label(str ) | Label explaining the use of the slider. |
options(Sequence, numpy.ndarray, pandas.Series, pandas.DataFrame, or pandas.Index) | Radio option labels. It will automatically cast to str. When using pandas.DataFrame, the first column will be selected as a source. |
value(a supported type or a tuple/list of supported types or None) | The value of the slider at the time it is first displayed. If a tuple/list of two values is supplied here, a range slider with those lower and upper limits will be created. Defaults to the first option. |
format_func(function) | Auxiliary function used to modify the radio option labels. The str values for the labels are passed as arguments, and it returns a modified str as per the function logic. This option is purely cosmetic and has no impact in the operation or return values of the radio widget. |
key(str or int ) | Unique key, string or integer, to reference the button in the code. The parameter is optional and will be automatically generated if not provided. |
help(str ) | Tooltip to be displayed when the cursor is hovered over the widget. |
on_change(callable) | Callback function invoked when the widget’s value changes. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict ) | Dictionary of keyword arguments to pass to the callback. |
disabled(bool ) | Boolean argument used to disable the widget. |
A
select slider is a version of the slider widget for nonnumerical, date, or time values. The following example replicates the one from the simple slider but with categorical values:
start_time, end_time = st.select_slider('Select time',
options=['nine', 'ten', 'eleven', 'twelve', 'one', 'two', 'three', 'four'],
value=('eleven', 'twelve'))
st.write('You are scheduled from **%s** to **%s**' % (start_time, end_time))
Text Input
A single-line text input
box can be added to our websites with the following command:
st.text_input(label, value, max_chars, key, type=’default’, help, autocomplete, on_change, args, kwargs, placeholder, disabled=False) ➤ str.
Table A-29st.text_input parameters
Parameter | Description |
---|
label(str ) | Label explaining the use of this input. |
value(any ) | Chose whether the checkbox is preselected by default when first rendered. Internally, this will be cast to str. |
max_chars(int or None) | Maximum number of characters permitted in text input. |
key(str or int ) | Unique key, string or integer, to reference the button in the code. The parameter is optional and will be automatically generated if not provided. |
type(str ) | Text input type: regular text input (the “default” option) or masked text (for type input “password”). |
help(str ) | Tooltip to be displayed when the cursor is hovered over the widget. |
autocomplete(str ) | The autocomplete attribute is a new method added to HTML 5. It is intended for websites that want the user to be able to complete a task without having access to their username and password. An optional value will be supplied to the <input> element’s autocomplete property. This value will be set to “new-password” for “password” input types and the empty string for “default” input types. More details in https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete. |
on_change(callable) | Callback function invoked when the widget’s value changes. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict ) | Dictionary of keyword arguments to pass to the callback. |
placeholder(str or None) | Optional string to be displayed if there is no text input. |
disabled(bool ) | Boolean argument used to disable the widget. |
The
example shows the use of mask text in a single-line text box:
password = st.text_input('Insert your password:', value='1234', max_chars = 24,
type = 'password')
st.write('The entered password is', password)
Number Input
A numeric input
widget can be added to our websites with the following command:
st.number_input(label, min_value, max_value, value=0.0, step=1, format, key, help, on_change, args, kwargs, disabled=False) ➤ int or float.
Table A-30st.number_input parameters
Parameter | Description |
---|
label(str ) | Label for the number input widget. |
min_value(int or float or None) | The minimum accepted value. |
max_value(int or float or None) | The maximum accepted value. |
value(int or float or None) | First render value of this widget. Defaults to min_value, or 0.0 if min_value is None. |
step(int or float or None) | The stepping interval. By default, set to 1 for int and 0.01 for all other options. For no specified values, it will default to the format parameter. |
format(str or None) | A custom format string that specifies how the interface should render numbers in a printf-style format. The return value is not affected by the conversion. %d, %e, %f, %g, and %i are supported for formatting int/float values. For date/time/datetime formatting, use Moment.js syntax: https://momentjs.com/docs/#/displaying/format/. |
key(str or int ) | Unique key, string or integer, to reference the button in the code. The parameter is optional and will be automatically generated if not provided. |
help(str ) | Tooltip to be displayed when the cursor is hovered over the widget. |
on_change(callable) | Callback function invoked when the widget’s value changes. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict ) | Dictionary of keyword arguments to pass to the callback. |
disabled(bool ) | Boolean argument used to disable the widget. |
A simple 1 to 100 selection, in steps of 1 unit, snippet implementation of the number input command is shown as
follows:
selection = st.number_input('Choose a number from 1 to 100:',
min_value = 0, max_value = 100, value = 50, step = 1)
st.write('The current number is ', selection)
Text Area
A multiline text
input can be added to our websites with the following command:
st.text_area(label, value, height, max_chars, key, help, on_change, args, kwargs, placeholder, disabled=False) ➤ str.
Table A-31st.text_area parameters
Parameter | Description |
---|
label(str ) | Label explaining the use of the input widget. |
value(any ) | Default text shown when the widget is first rendered. Internally, this will be cast to str. |
height(int or None) | Height in pixels of the UI element. |
max_chars(int or None) | The maximum number of characters permitted in the text area. |
key(str or int ) | Unique key, string or integer, to reference the button in the code. The parameter is optional and will be automatically generated if not provided. |
help(str ) | Tooltip to be displayed when the cursor is hovered over the widget. |
on_change(callable) | Callback function invoked when the widget’s value changes. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict ) | Dictionary of keyword arguments to pass to the callback. |
placeholder(str or None) | A string that will be displayed when the text area is empty. |
disabled(bool ) | Boolean argument used to disable the widget. |
The multiline
text input widget can be used as follows:
text = st.text_area(label = 'Insert text:', value = "Hello world", height = 50)
st.write('Entered text: **%s**' % text)
Date Input
A date
display input widget can be added to our websites using the following command:
st.date_input(label, value, min_value, max_value, key, help, on_change, args, kwargs, disabled=False) ➤ value.
Table A-32st.date_input parameters
Parameter | Description |
---|
label(str ) | Label explaining the intent of the date selection. |
value(datetime.date or datetime.datetime or list/tuple of datetime.date or datetime.datetime or None) | Value showed by this widget during the first render. If a list/tuple is provided with zero to two date/datetime values, it will be considered as a range. Today is the default value if nothing is selected. |
min_value(datetime.date or datetime.datetime) | The default minimum selectable date. If the value is a date, it will be set to 10 years from now. For intervals [start, finish], start – 10 years is assumed. |
max_value(datetime.date or datetime.datetime) | The maximum selectable date. If the value is a date, it will be updated with 10 years added. If the value is the period [start, end], it will be updated to end + 10 years. |
key(str or int ) | Unique key, string or integer, to reference the button in the code. The parameter is optional and will be automatically generated if not provided. |
help(str ) | Tooltip to be displayed when the cursor is hovered over the widget. |
on_change(callable) | Callback function invoked when the widget’s value changes. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict) | Dictionary of keyword arguments to pass to the callback. |
disabled(bool ) | Boolean argument used to disable the widget. |
The following lines of code implement a simple age in days calculator with the date input widget, limiting the lower value to those born after
1920:
birth_date = st.date_input('Date of Birth:', value = datetime.date(2018,12,29), min_value = datetime.date(1920,1,1))
st.write('Your age in days:', datetime.date.today() - birth_date)
Time Input
A time input
widget can be added to our websites using the following command:
st.time_input(label, value, key, help, on_change, args, kwargs, disabled=False) ➤ value.
Table A-33st.time_input parameters
Parameter | Description |
---|
label(str ) | Label of the widget. |
value(datetime.time/datetime.datetime) | Value showed by this widget during the first render. Cast internally to str. Current time is the default. |
key(str or int ) | Unique key, string or integer, to reference the button in the code. The parameter is optional and will be automatically generated if not provided. |
help(str ) | Tooltip to be displayed when the cursor is hovered over the widget. |
on_change(callable) | Callback function invoked when the widget’s value changes. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict ) | Dictionary of keyword arguments to pass to the callback. |
disabled(bool ) | Boolean argument used to disable the widget. |
The example shows the use of the time input with a default value at render time of 7.00
am:
sleep_time = st.time_input('How many hours of sleep are enough? ', datetime.time(7, 00))
st.write('At least ', sleep_time)
File Uploader
A
file uploader can be added to our websites using the following command:
st.file_uploader(label, type=None, accept_multiple_files=False, key, help, on_change, args, kwargs, disabled=False) ➤ list. The default value for uploaded files is 200MB. This value is configurable using the server.maxUploadSize config option.
Table A-34st.file_uploader parameters
Parameter | Description |
---|
label(str ) | Label of the widget explaining what files are expected to be uploaded. |
type(str or list of str or None) | Array of allowed extensions, i.e., [‘gif’, ‘jpg’]. To allow all extensions, use None. |
accept_multiple_files(bool ) | When True, it allows the user to upload multiple files at the same time and will return the list of the uploaded files. False is the default option. |
key(str or int ) | Unique key, string or integer, to reference the button in the code. The parameter is optional and will be automatically generated if not provided. |
help(str ) | Tooltip to be displayed when the cursor is hovered over the widget. |
on_change(callable) | Callback function invoked when the widget’s value changes. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict ) | Dictionary of keyword arguments to pass to the callback. |
disabled(bool ) | Boolean argument used to disable the widget. |
The following code can be used to upload multiple files together.
files_to_upload = st.file_uploader(label = 'Upload photos:', accept_multiple_files=True)
Camera Input
The camera input
widget can be used to return static footage from the user’s webcam using the command
st.camera_input(label, key, help, on_change, args, kwargs, disabled=False) ➤ any.
Table A-35st.time_input parameters
Parameter | Description |
---|
label(str ) | Label of the widget. |
key(str or int ) | Unique key, string or integer, to reference the widget in the code. The parameter is optional and will be automatically generated if not provided. |
help(str ) | Tooltip to be displayed when the cursor is hovered over the widget. |
on_change(callable) | Callback function invoked when the widget’s value changes. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict ) | Dictionary of keyword arguments to pass to the callback. |
disabled(bool ) | Boolean argument used to disable the widget. |
The following example shows how to use the camera input command to take a photo with your webcam and read the text in the image using optical character recognition:
import pytesseract
from PIL import Image
pytesseract.pytesseract.tesseract_cmd = r'C:Program FilesTesseract-OCR esseract.exe'
photo = st.camera_input('Take a photo')
if photo is not None:
st.subheader('Your text:')
text = pytesseract.image_to_string(Image.open(photo))
st.write(text)
Color Picker
A color picker
widget can be added to our websites using the following command:
st.color_picker(label, value, key, help, on_change, args, kwargs, disabled=False) ➤ str.
Table A-36st.color_picker parameters
Parameter | Description |
---|
label(str ) | Label explaining the use of the widget. |
value(str ) | Hex value showed by this widget during the first render. If None, it will default to black. |
key(str or int ) | Unique key, string or integer, to reference the button in the code. The parameter is optional and will be automatically generated if not provided. |
help(str ) | Tooltip to be displayed when the cursor is hovered over the widget. |
on_change(callable) | Callback function invoked when the widget’s value changes. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict ) | Dictionary of keyword arguments to pass to the callback. |
disabled(bool ) | Boolean argument used to disable the widget. |
The following code shows the color selection widget implementation, with black (hexadecimal value #000000) as the default selection.
color = st.color_picker(label = 'Select a Color', value = '#000000')
Forms
You may encapsulate several
widgets together into one form using Streamlit’s
st.form(key, clear_on_submit=False) command. The added benefit of using a form is that Streamlit will not rerun the entire script each time you interact with one of the widgets within it, as it normally would. Instead, Streamlit will only rerun once you click the associated button using the command
st.form_submit_button(label=’Submit’, help=None, on_click, args, kwargs) ➤ bool.
Table A-37st.form parameters
Parameter | Description |
---|
key(str ) | A unique string that may be used to identify the form. |
clear_on_submit(bool ) | If this argument is set to true, all of the widgets inside the form will be reset to their default values after the form submit widget’s value changes. |
Table A-38st.form_submit_button parameters
Parameter | Description |
---|
label(str ) | Label to be displayed in the button. |
help(str or None) | Tooltip to be displayed when the cursor is hovered over the widget. |
on_click(callable) | Callback function called when the button is clicked. |
args(tuple) | Tuple of arguments to pass to the callback. |
kwargs(dict ) | Dictionary of keyword arguments to pass to the callback. |
The following example shows how a Streamlit form and form submit button may be used
together:
with st.form('form_1'):
radio = st.radio('Radio button', ['Hello','World'])
checkbox = st.checkbox('Hello world')
if st.form_submit_button('Submit form'):
st.write('Radio: **%s**' % radio, 'Checkbox:', checkbox)
Displaying Interactive Widgets
Streamlit makes it rather simple to render multimedia content regardless of its source. Whether it is a local image saved on disk, or a video accessed via a URL, or even an array with the raw data of a sound file, you have the ability to display and play multimedia using Streamlit’s native commands without any further effort on your behalf.
Displaying Images
We can easily insert
images using the following command:
st.image(image, caption, width, use_column_width, clamp, channels=‘RGB’, output_format=‘auto’).
Table A-39st.image parameters
Parameter | Description |
---|
image(numpy.ndarray, [numpy.ndarray], BytesIO, str, or [str] ) | One or a list of the following: monochrome image (w,h) or (w,h,1), color image (w,h,3), RGBA image (w,h,4), URL of image, path of a local image, VG XML string. |
caption(str or list of str ) | Image caption. A list of captions should be used if multiple images are displayed (one per image). |
width(int or None) | Image width. None uses the image size as long as it does not exceed the width of the column. SVG images must use this option as they have no default image width. |
use_column_width(‘auto’ or ‘always’ or ‘never’ or bool ) | “auto” uses the natural image size without exceeding the width of the column. True or “always will use the column width. False or “never” uses the image’s natural size. Note: use_column width takes precedence over the width parameter. |
clamp(bool ) | Only applicable for byte array images and ignored for image URLs. Clamp will set the pixel values to a valid range ([0–255] per channel). If required and not set, the image will have out-of-range values, and an error will be thrown. |
channels(‘RGB’ or ‘BGR’ ) | For nd.array, this parameter indicates the color information. Defaults to “RGB,” or [:, :, 0] for red, [:, :, 1] for green, and [:, :, 2] for blue. Some libraries might use a different coding, like OpenCV that uses “BGR.” |
output_format(‘JPEG’, ‘PNG’, or ‘auto’ ) | Parameter to specify the image transfer format. JPEG for photos for lossy compression; PNG for diagrams for lossless compression. The default option “auto” selects the compression based on the image type. |
The
following example displays a PNG as a static image:
Displaying an Audio Player
An
audio player can be displayed using the following command:
st.audio(data, format=’audio/wav’, start_time).
Table A-40st.audio parameters
Parameter | Description |
---|
data(str, bytes, BytesIO, numpy.ndarray, or file opened with) | Uses the standard io.open() function and accepts raw audio data, a filename, or a URL to an audio file. Raw data formats and Numpy arrays must include the minimum required structure and values for its type. |
start_time(int ) | Time in seconds to set the widget slider to start playing by default. |
format(str ) | Audio file MIME type. “audio/wav” is the default. See https://tools.ietf.org/html/rfc4281 for more info. |
Inserting an audio file can be done in one line of code as follows:
st.audio('snoring.mp3', start_time=10)
Displaying Video
A
video can be added to our websites with the command
st.video(data, format=’video/mp4’, start_time).
Table A-41st.video parameters
Parameter | Description |
---|
data(str, bytes, BytesIO, numpy.ndarray, or file opened with) | Uses the standard io.open() function and accepts raw video data, a filename, or a URL to a YouTube or video file. Raw data formats and Numpy arrays must include the minimum required structure and values for its type. |
format(str ) | Video file MIME type. “audio/mp4” is the default. See https://tools.ietf.org/html/rfc4281 for more info. |
start_time(int ) | Time in seconds to set the widget slider to start playing by default. |
A simple example of the insertion of a video is shown as follows:
st.video('https://www.youtube.com/watch?v=m0h7ESBEf3U')
Page Structure
With Streamlit, you have four ways of organizing the web page. Namely, you may utilize a sidebar, multiple columns, expanders, and containers or combinations of them together to customize the user experience. In addition, you may use placeholders to effectively reserve space on your web page in order to use in due course on demand.
Sidebar
Streamlit provides a sidebar with the st.sidebar command that may be expanded, contracted, or left to automatically deploy based on the page size. In addition, you may add any other widget or element to it (with the exception of st.echo and st.spinner) by appending the function to it.
The following example displays how to use a sidebar with another Streamlit element:
st.sidebar.title('Hello world')
Columns
With
columns, you may divide the web page into vertical sections with specified widths using the command
st.columns(spec) ➤
list. This command returns a list of columns that can then be invoked using a
with statement.
Table A-42st.columns parameters
Parameter | Description |
---|
spec(int or list of numbers) | An integer will specify the number of columns of equal width to create. If a list of numbers is used, a column for each number with a width proportional to the number will be created. |
The following example displays how to use columns within a Streamlit application:
col1, col2 = st.columns([1,2])
with col1:
st.text_input('Hello')
with col2:
st.text_input('World')
Expander
Streamlit provides an expander
widget with the
st.expander(label, expanded) command that may be expanded or contracted on demand and can host all other widgets or elements within it by using a
with statement.
Table A-43st.expander parameters
Parameter | Description |
---|
label(str ) | The displayed name of the expander widget. |
expanded(boolean) | Setting this parameter to True will set the widget to an expanded state on start. |
The following example shows how to use an expander with another Streamlit element:
with st.expander('Hello world'):
st.title('Hello world')
Container
Using Streamlit’s st.container() command, you may group several elements together within an invisible container. Elements can be added to a container using a with statement or by appending the Streamlit element after the name of the container. Elements can be added to a container on demand and out of order.
The following
example shows how to use a container within a Streamlit application:
container_1 = st.container()
container_1.write('Hello')
st.text_input('Hello world')
container_1.write('World')
Placeholder
Streamlit allows you to reserve places within your web page by using placeholders that can be invoked with the command
st.empty(). You may add any single element (or group of elements within a container) to the placeholder using a
with statement or by simply appending the element after the name of the placeholder. You may update the element on demand or replace it with another at any given time, and once you are done, you may empty the placeholder by appending
empty() to it. Placeholders are particularly useful for generating dynamic or animated content that needs to be updated regularly.
while datetime.datetime.now() < datetime.datetime(2022, 1, 12):
clock.metric(label='Clock', value=datetime.datetime.now().strftime('%H:%M:%S'))
Displaying Status and Progress
Depending on your application, you may need to display the status and/or progress of a certain activity to the user. With Streamlit, we have multiple native methods to communicate to the user as to exactly what stage an operation is at.
Progress Bar
With Streamlit’s
st.progress(value) command, you have the ability to display in real time the progress of any
activity.
Table A-44st.progress parameters
Parameter | Description |
---|
value(int or float ) | The value of the progress bar when it renders. Values range from 0 to 100 for int and 0.0 to 1.0 for float. |
for i in range(0,100):
timer.progress(i)
time.sleep(1)
Spinner
Using Streamlit’s
st.spinner(text) command, you can display a temporary message within a block of executable
code.
Table A-45st.spinner parameters
Parameter | Description |
---|
text(str ) | The message to render temporarily while executing the block of code. |
for i in range(0,100):
with st.spinner('Time remaining: **%s seconds**' % (100-i)):
time.sleep(1)
Messages
With the commands
st.success(body),
st.info(body),
st.warning(body), and
st.error(body), you have the ability to display messages with green, blue, yellow, and red encapsulating boxes,
respectively.
Table A-46st.success, st.info, st.warning, and st.error parameters
Parameter | Description |
---|
body(str ) | The message to render. |
col1, col2, col3, col4 = st.columns(4)
with col1:
st.success('Hello world')
with col2:
st.info('Hello world')
with col3:
st.warning('Hello world')
with col4:
st.error('Hello world')
Exception
With Streamlit’s
st.exception(exception) command, you can display a type of exception and a corresponding
message.
Table A-47st.exception parameters
Parameter | Description |
---|
exception(Exception) | The type of exception to render. |
try:
a/b
except:
st.exception(ZeroDivisionError('Division by zero'))
Balloons
The
st.balloons() command gives you the ability to render floating balloons should you find it absolutely necessary to do so:
Snow
And lastly, the
st.snow() command gives you the ability to render floating snowflakes in spirit of Streamlit’s acquisition by Snowflake:
Utilities
A host of other functions and added utilities come with Streamlit, such as the ability to configure the web page programmatically, to render code snippets, and to provide object documentation if required.
Page Configuration
You can configure the
title, icon, layout, sidebar state, and menu options of your Streamlit application using the
st.set_page_config(page_title, page_icon, layout, initial_sidebar_state, menu_items) command.
Table A-48st.set_page_config parameters
Parameter | Description |
---|
page_title(str or None) | The title that will appear on the browser’s tab; if not invoked, the script name will be used as the page title. |
page_icon(image, icon, str, or None) | The favicon that will be displayed on the browser’s tab; shortcodes may also be used as an alternative to images. |
layout(’centered’ or ’wide’ ) | The layout of the page; if not invoked, the page will default to centered. |
initial_sidebar_state(’auto’, ’expanded’, or ’collapsed’ ) | The state of the sidebar when the page starts; if not invoked, it will default to auto. |
menu_items(dict ) | Configuration for the Get help, Report a bug, or About pages within the hamburger menu. For further information, please refer to Section 3.1. |
st.set_page_config(
page_title='Hello world',
page_icon=icon,
layout='centered',
initial_sidebar_state='auto',
menu_items={
'Get Help': 'https://streamlit.io/',
'Report a bug': 'https://github.com',
'About': 'About your application: **Hello world**'
}
)
Code Echo
You can render code and execute it simultaneously by using the
st.echo(code_location) command.
Table A-49st.echo parameters
Parameter | Description |
---|
code_location(’above’ or ’below’ ) | Whether to render the code above or below its execution location. |
with st.echo():
st.write('Hello world')
Documentation
You may display the help documentation associated with an object by using the
st.help(obj) command.
Table A-50st.help parameters
Parameter | Description |
---|
obj(Object ) | The object whose help documentation should be displayed. |
lst = [1,2,3]
st.help(lst)
Stop Execution
To stop the
execution of a Streamlit application at a specific point in your script, you may use the
st.stop() command to prevent the rest of your code from being executed:
st.write('Hello world')
st.stop()
st.write('Bye world')
Session State Management
Implementing a stateful architecture can be essential for a multitude of web applications. From storing session-specific data such as user credentials to other variables, the absence of such an ability can be a deal breaker for many developers. Just imagine trying to implement logical flow in your application, where a user input in one page is used to generate a visualization in another page. Without storing the input as a session variable, it would be reset once you navigate to the other page or simply rerun the script, leaving you without a visualization. Luckily, Streamlit offers a native and highly intuitive way of managing session state seamlessly that enables developers to cater for an enhanced user experience.
Initializing Session State Variables
Streamlit’s session state
dictionary is composed of key-value pairs where each key must be initialized before it can be invoked, and each value can consist of a string, integer, list, dictionary, dataframe, object, or other variables. To initialize a variable into your session state, proceed as follows:
if 'state_1' not in st.session_state:
st.session_state['state_1'] = None
Accessing Session State Variables
Subsequently, to access the variable initialized within the same session, simply invoke it as follows:
state_1 = st.session_state['state_1']
To access all of the session state variables, use the following command:
st.write(st.session_state)
This will return the session state dictionary with all of the key-value pairs stored as follows:
Updating Session State Variables
To update the value of the session state
variable, proceed as follows:
st.session_state['state_1'] = 'Hello world'
Deleting Session State Variables
To delete a specific session state
variable, use the following:
del st.session_state['state_1']
In order to delete all of the session state variables at once, you may use the following:
for variable in st.session_state:
del st.session_state[variable]
Widget Session State
Each widget in Streamlit is automatically associated with its own session state variable, where the key is the same key that is invoked as an argument to the widget, as shown in the following:
st.button('Random button',key='random_button_1')
st.text_input('Hello world',key='hello_world_input')
st.write(st.session_state)
Please note that modifying the value of a widget’s session state after instantiating it is not permitted, and should you attempt to do so, a StreamlitAPIException error will be thrown. However, setting the state of a widget before it is instantiated is permitted, albeit with a one-time warning message if the default value of the widget has already been set as an argument. In addition, widgets with buttons such as st.button, st.download_button, and st.file_uploader cannot have their session state values modified; by default, they are set to False and will be toggled to True when they are clicked.
Data Management
Managing data for optimal use of computing resources is of utmost importance for web servers. Given the large scale of data that we are exposed to, it is often essential to cache data, functions, and other objects for prompt reuse when the need arises. To that end, Streamlit offers an in-house capability to cache and reuse data in our applications with tangibly positive outcomes. Furthermore, Streamlit also offers the ability to mutate data natively without any third-party libraries should the need arise.
Caching Data
Streamlit allows you to cache the results and data of a function persistently for later use with the
st.cache(func, persist, allow_output_mutation, show_spinner, suppress_st_warning, hash_funcs, max_entries, ttl) command. This feature is particularly useful if you are working with large datasets that will take an extended period of time to download or process. With this feature, you can enter your data into the cache by invoking the function written below the
st.cache decorator and then recall it on demand when needed without having to reexecute the function, even after your script has been rerun.
Table A-51st.cache parameters
Parameter | Description |
---|
func(callable) | The function to be cached. |
persist(boolean) | This parameter specifies whether to keep the cached data persistently or not. |
allow_output_mutation(boolean) | Setting the parameter to True will allow you to override the cached data without receiving a warning from Streamlit. |
show_spinner(boolean) | If set to True, a spinner will be displayed when there is a cache miss. |
suppress_st_warning(boolean) | Setting this parameter to True will suppress any warnings about calling embedded functions within a cached function. |
hash_funcs(dict or None) | With this parameter, you can override the reaction of Streamlit to objects within the cache; when the hasher encounters a specified object within the dict, it will use the associated function in response. |
max_entries(int or None) | This parameter specifies the maximum number of items to cache, and whenever a new item is added to the list, the oldest item will be removed accordingly. |
ttl(float or None) | This parameter determines the time in seconds to keep an item in the cache; if not invoked, the cache will not be cleared. |
Caching with
st.cache:
@st.cache
def dataframe(rows):
df = pd.DataFrame(
np.random.randn(rows, 5),
columns=('col %d' % i for i in range(5)))
return df
# Initial invocation to cache dataframe
df = dataframe(100000)
# Subsequent invocation will access the cached dataframe without re-executing function
df = dataframe(100000)
# Will re-execute function and recache new dataframe due to modified input parameter
df = dataframe(200000)
Caching Functions
Streamlit also allows you to cache function executions persistently with the
st.experimental_memo(func, persist, show_spinner, suppress_st_warning, max_entries, ttl) command. This feature is indeed very similar to the
st.cache command. And when you no longer need the cache, you may remove it by using the command
st.experimental_memo.clear(). Please note that commands beginning with
experimental will have this prefix removed in future releases once the command has matured.
Table A-52st.experimental_memo parameters
Parameter | Description |
---|
func(callable) | The function to be cached. |
persist(boolean) | This parameter specifies whether to keep the cached data persistently or not. |
show_spinner(boolean) | If set to True, a spinner will be displayed when there is a cache miss. |
suppress_st_warning(boolean) | Setting this parameter to True will suppress any warnings about calling embedded functions within a cached function. |
max_entries(int or None) | This parameter specifies the maximum number of items to cache, and whenever a new item is added to the list, the oldest item will be removed accordingly. |
ttl(float or None) | This parameter determines the time in seconds to keep an item in the cache; if not invoked, the cache will not be cleared. |
Caching with
st.experimental_memo:
@st.experimental_memo
def dataframe(rows):
df = pd.DataFrame(
np.random.randn(rows, 5),
columns=('col %d' % i for i in range(5)))
return df
# Initial invocation to cache function execution
df = dataframe(100000)
# Subsequent invocation will access the cached execution without re-executing function
df = dataframe(100000)
# Will re-execute function and recache the new execution due to modified input parameter
df = dataframe(200000)
Caching Objects
Similar to
st.cache,
Streamlit allows you to cache objects persistently with the
st.experimental_singleton(func, show_spinner, suppress_st_warning) command. And when you no longer need the cache, you may remove it by using the command
st.experimental_singleton.clear(). It is important to highlight that singleton objects must be thread-safe since they will be shared by all users of the application. Possible use cases for
st.experimental_singleton are database connections and corpora. However, this is not the case for
st.memo as each caller will receive their own copy of the cached data.
Table A-53st.experimental_singleton parameters
Parameter | Description |
---|
func(callable) | The function to be cached. |
show_spinner(boolean) | If set to True, a spinner will be displayed when there is a cache miss. |
suppress_st_warning(boolean) | Setting this parameter to True will suppress any warnings about calling embedded functions within a cached function. |
Caching with
st.experimental_singleton:
@st.experimental_singleton
def load_nlp(lang):
nlp = spacy.load('%s_core_news_sm' % (lang))
return nlp
# Initial invocation to cache object
nlp = load_nlp('es')
# Subsequent invocation will access the cached object without re-executing function
nlp = load_nlp('es')
# Will re-execute function and recache new object due to modified input parameter
nlp = load_nlp('de')
Mutate Data
Streamlit allows you to mutate your data and charts in real time by adding a dataframe to the end of a table using the
st.add_rows(data,**kwargs) command.
Table A-54st.add_rows parameters
Parameter | Description |
---|
data(Pandas dataframe or styler, PyArrow table, Numpy array, dict, None, or iterable) | The dataframe to be appended to an existing table. If a PyArrow table is used, you must set the dataFrameSerialization = ’arrow’ in the config file; for further information, please refer to Section 3.1. |
**kwargs(Pandas dataframe, Numpy array, dict, None, or iterable) | Should you need to do so, you can pass the dataframe to append as a named object, i.e., ’dataset’ = df. |
Mutating tables with
st.add_rows:
table = st.table(pd.DataFrame(data={'a':[1,2], 'b':[3,4]}))
df = pd.DataFrame(data={'a':[5,6], 'b':[7,8]})
table.add_rows(df)
The Hamburger Menu
Streamlit by default is equipped with a hamburger menu at the top-right corner of the web page. This menu provides a host of additional features that may be of use to the user and developer alike. Table
A-55 summarizes the available features.
Table A-55Hamburger menu features
Feature | Description |
---|
Return | When clicked, Streamlit will rerun the script from top to bottom. |
Settings | Opens a window where the user can customize the theme’s appearance, color, font, and other associated settings. For further information, please refer to Section 3.1. |
Record a screencast | As the name suggests, this feature allows you to record the video and audio feed from your browser window and save it in the webm format. |
Report a bug | This option opens a link to the GitHub page where you can report a bug. Alternatively, you may choose to link this option to any other URL you require as shown in Section 3.1. |
Get help | Similarly, this option takes you to the Streamlit discussion page where you can raise concerns and ask questions. It may be linked to another URL if required as shown in Section 3.1. |
About | This option displays a modal window with the version of Streamlit that you are using. If needed, you may customize the text displayed as shown in Section 3.1. |
Clear cache | This feature will clear any data stored by the st.cache command. For further information, please refer to Section 4.1. |
Deploy this app | Streamlit allows you to deploy your application to their server referred to as Streamlit Cloud directly with this option. |
Streamlit Cloud | This link takes you to the home page for Streamlit Cloud that provides further information about their hosting service. |
Report a Streamlit bug | Identical to the Report a bug feature, this option will take you to the GitHub page where you can raise bugs and concerns. |
Visit Streamlit docs | This link will simply take you to Streamlit’s API. |
Visit Streamlit forums | Likewise, this link will take you to Streamlit’s forum. |