st.toggle() in Streamlit
The st.toggle() method in Streamlit is a switch-like widget that lets users choose between ON and OFF states. It works like a checkbox but provides a modern toggle design.
Syntax
st.toggle(label, value=False, key=None, help=None, on_change=None,
args=None, kwargs=None, *, disabled=False,
label_visibility="visible", width="content") The function has the following parameters:
- label label (str): Text shown next to the toggle.
- value (bool): Default state (True or False). Default is False.
- help: Tooltip text displayed on hover.
- disabled: If True, the toggle is not clickable.
- label_visibility: Controls label visibility — "visible", "hidden", or "collapsed".
Example: Basic Toggle
Python
# Importing the Streamlit library
import streamlit as st
# Create a toggle switch (default ON)
toggle_state = st.toggle(
"Enable feature",
value=True,
help="Turn this ON to enable the feature"
)
# Display message based on toggle state
if toggle_state:
st.success("✅ Feature is enabled")
else:
st.warning("⚠️ Feature is disabled") Explanation
- Toggle starts ON because value=True.
- When enabled, a success message is displayed.
- When disabled, a warning message is shown.
The output of the above code is shown below:
