st.button() method in Streamlit
The button() method in Streamlit creates a clickable button that runs code when pressed. It is commonly used for triggering actions such as submitting a form, refreshing data, running a function, or starting a process.
Syntax
st.button(
label,
key=None,
help=None,
on_click=None,
args=None,
kwargs=None,
*,
type="secondary",
icon=None,
disabled=False,
use_container_width=None,
width="content"
) Parameters
- label: Text shown on the button.
- key: Unique identifier if multiple buttons share the same label.
- help: Tooltip text displayed on hover.
- on_click: Function to call when the button is clicked.
- args / kwargs: Arguments passed to the on_click function.
- type: "primary" (highlighted) or "secondary" (default).
- disabled: If True, the button is not clickable.
Example: Basic Button
Python
import streamlit as st
if st.button("Click Me"):
st.write("Button was clicked!") ✅ The code inside the if block runs only once when the button is clicked.
Example: Button with Action
Python
import streamlit as st
def greet(name):
st.write(f"Hello, {name}!")
if st.button("Say Hello"):
greet("Ashish") Example: Primary Button
Python
import streamlit as st
if st.button("Save", type="primary"):
st.success("Data saved successfully!") Example: Using on_click
Python
import streamlit as st
def process():
st.write("Processing started...")
st.button("Run Process", on_click=process) Important Notes
- st.button() does not stay active — it returns True for one run when clicked, then resets to False.
- For persistent states (like a toggle), use st.checkbox() or st.toggle() instead.