Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 38 ยท Input Widgets

Buttons, Checkboxes and Toggles

Learn Streamlit button behavior: buttons are True for one rerun, nested buttons vanish, and checkboxes and toggles keep state. Add download and link buttons.

Widgets are how users talk to your app. This chapter covers them one family at a time, starting with the simplest: things you press or flip. A button runs an action once, a checkbox or toggle holds an on/off value, a download button hands over a file.

All Streamlit code here is real and read-only; its result is described. Runnable blocks show the behavior with a stand-in rerun engine, and the pandas code that prepares downloads.

st.button: true for one run

Python
import streamlit as st

if st.button("Say hello"):
    st.write("Hello!")
else:
    st.write("Click the button.")

At first the page shows a button labelled "Say hello" and the text "Click the button." Click it: the script reruns, st.button returns True this time, and the page shows "Hello!" Click anywhere else (or any other widget) and the script reruns again, the button returns False, and the text goes back to "Click the button." The result of a button is not remembered. That is the rerun model from an earlier lesson.

Useful arguments:

Argument Effect
type="primary" / "secondary" / "tertiary" Visual emphasis: filled, outlined (default), or text-like
icon=":material/save:" Adds an icon
disabled=True Grays the button out
help="..." Tooltip
key="save" Stable identity; also required when two widgets have identical labels
on_click=fn A callback run before the script reruns (see Forms and Callbacks)
width="stretch" Full width of the column (older versions: use_container_width=True)

The nested-button trap

Beginners often write a button inside another button's if block:

Python
if st.button("Load data"):
    st.write("Loaded.")
    if st.button("Process"):        # never works as expected
        st.write("Processed.")

Click "Load data": the page shows "Loaded." and a "Process" button. Click "Process": the script reruns, but now "Load data" is False (it was only true in the previous run), so the inner block is skipped, and "Process" disappears. The inner click is lost.

The stand-in below is not Streamlit; it reproduces that logic with a tiny rerun engine, then shows the fix, which is to keep the first decision in state. Real code uses st.session_state for that, as in the State and Caching chapter.

Python Stand-in: why nested buttons break

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With nesting, the "Process" click shows an empty page. With state, "Processed." appears. A second fix for simple cases is to avoid the nesting entirely and use st.checkbox or st.toggle, which do remember their value.

Checkboxes and toggles

st.checkbox and st.toggle return a boolean that stays true until the user changes it:

Python
import streamlit as st

show_raw = st.checkbox("Show raw data")
dark = st.toggle("Dark mode preview", value=True)

if show_raw:
    st.write("Here is the raw data...")
st.write("Dark mode is", "on" if dark else "off")

The page shows a square checkbox labelled "Show raw data" (unchecked), and a sliding switch labelled "Dark mode preview" (on). Ticking the checkbox makes the extra line appear immediately and it stays visible while other widgets change. Use a checkbox for an option in a list of options; use a toggle for an immediate on/off setting. Both accept value= for the default, disabled, help and key.

This is the usual way to show and hide parts of an app:

Python
if st.checkbox("Show summary statistics"):
    st.write(df.describe())

st.download_button

The download button sends data from the server to the user's computer. You pass the data itself, a file name and a MIME type:

Python
import pandas as pd
import streamlit as st

df = pd.DataFrame({"name": ["Ada", "Bob"], "score": [90, 75]})

st.download_button(
    label="Download CSV",
    data=df.to_csv(index=False).encode("utf-8"),
    file_name="scores.csv",
    mime="text/csv",
)

The page shows a "Download CSV" button; clicking it saves scores.csv (a header line and two rows) through the browser. data can be a string, bytes or a file object, so it works for CSV, JSON, images, PDFs and ZIPs. Because the data is built on every rerun, compute heavy files once and cache them. In recent versions the download button can run without rerunning the app (on_click="ignore"), which is helpful when the file is large.

Prepare the bytes with ordinary Python, and you can check what the user would receive:

Python Build the bytes for a download button

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For a download of an Excel file you would write to an io.BytesIO buffer with df.to_excel(buffer) (needs openpyxl) and pass buffer.getvalue() with the Excel MIME type.

st.link_button("Open docs", "https://docs.streamlit.io") shows a button that opens a URL in a new tab; it never reruns the script. Inside an app with several pages, st.page_link("pages/report.py", label="Go to report") links to another page (see Multipage Apps).

Disabling and confirming

A button that deletes something should not fire on a single accidental click. Streamlit has no built-in confirm dialog on a button, but you can combine widgets:

Python
confirm = st.checkbox("I understand this deletes all rows")
if st.button("Delete everything", type="primary", disabled=not confirm):
    st.warning("Deleted.")

The red-style button stays disabled until the box is ticked. The Layout chapter shows st.dialog, a proper modal confirmation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does st.button return True?

    A button's value is not remembered between reruns.
  2. 2. Why does an inner st.button inside another button's if-block not work?

    Clicking the inner button reruns the script; the outer button is now False, so the code containing the inner button never runs.
  3. 3. Which widgets keep their True/False value across reruns?

    Checkboxes and toggles store their state; buttons do not.
  4. 4. What must you pass to st.download_button besides a label?

    The data (string, bytes or file object) is required; file name and MIME type tell the browser how to save it.

Summary

  • st.button is True only during the rerun it triggers, so never nest buttons; store state or use a checkbox instead.
  • st.checkbox and st.toggle remember a boolean and are the normal way to show or hide content.
  • st.download_button serves bytes or text you prepare; build and cache the data first.
  • st.link_button opens URLs; st.page_link jumps between pages.

Next: Text and Number Input