Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 38 ยท Input Widgets

Forms and Callbacks

Batch inputs with st.form so the app reruns once on submit, and use on_click and on_change callbacks that run before the script. Includes ordering rules and common mistakes.

By default every widget reruns the script the moment it changes. That is magical for a slider, and wasteful for a sign-up form: a user typing a name, an email and a date would trigger three reruns before they have finished. Streamlit has two tools to take control. Forms hold widgets back until the user presses a submit button. Callbacks are functions that run when a widget changes, before the script restarts.

The Streamlit code is real and read-only; the visible result is described. Runnable stand-ins imitate the rerun engine so you can count the runs and see the order of events.

st.form: submit everything at once

Python
import streamlit as st

with st.form("signup"):
    name = st.text_input("Name")
    age = st.number_input("Age", min_value=0, max_value=120, value=30)
    agree = st.checkbox("I accept the terms")
    submitted = st.form_submit_button("Create account")

if submitted:
    if not name:
        st.error("Please enter a name.")
    elif not agree:
        st.warning("You must accept the terms.")
    else:
        st.success(f"Welcome, {name}! (age {age})")

The page shows a bordered box containing a text box, a number box, a checkbox and a "Create account" button. Type a name, change the age, tick the box: nothing reruns. Click "Create account": the script reruns once, all three values arrive together, and submitted is True for that run. The success message appears below the form.

Rules of forms:

  • Use with st.form("unique_key"): (the key must be unique on the page), or form = st.form(...) and form.text_input(...).
  • Every form needs exactly one st.form_submit_button, inside the form.
  • Widgets inside a form do not rerun the app when changed. Their values update when the submit button is pressed.
  • A normal st.button is not allowed inside a form; use form_submit_button. st.download_button is not allowed either.
  • Pressing Enter in a text box also submits the form.
  • clear_on_submit=True resets all the form's widgets to their defaults after submit, good for "add another entry" forms.
  • Anything that should react immediately (for example a selectbox that changes the options of another) belongs outside the form.
flowchart LR
    A["Type, tick, choose<br/>inside the form"] -->|"no rerun"| A
    A -->|"click submit"| B["One rerun<br/>with all values"]
    B --> C["submitted = True<br/>handle the data"]

Edits inside a form stay in the browser until the user submits.

Counting reruns (stand-in)

The following block is not Streamlit. It counts how many times a script would run for the same three edits, with live widgets versus a form.

Python Stand-in: reruns with and without a form

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.

(In a real app a text box applies on Enter or when focus is lost, not on each keystroke, but a typical multi-field form still causes many reruns without a form.)

Forms for expensive work

Forms also protect slow code. If changing a parameter would retrain a model or run a big query, put the parameters in a form so the work happens only when the user is ready. This is a common pattern for machine learning demos.

Callbacks: on_click and on_change

Most widgets accept on_click (buttons) or on_change (everything else). The function you pass is called when the user interacts, and the key fact is the order:

  1. The user interacts with the widget.
  2. Streamlit runs your callback.
  3. Then the script reruns from the top.

So callbacks are the right place to change state that the rerun will then display, and the widget's new value is already available to the callback through st.session_state[key].

Python
import streamlit as st

if "count" not in st.session_state:
    st.session_state.count = 0

def add_one(step):
    st.session_state.count += step

st.button("Add 5", on_click=add_one, args=(5,))
st.button("Add 1", on_click=add_one, kwargs={"step": 1})
st.write("Count:", st.session_state.count)

The page shows two buttons and "Count: 0". Click "Add 5": add_one(5) runs first and raises the count, then the script reruns and the text reads "Count: 5". Because the callback ran before the rerun, the text is up to date. Without the callback, you would need an if st.button(...) block above the st.write, and it would be easy to display the old value. Pass arguments with args=(...) and kwargs={...}.

An on_change example, with a key so the callback can read the new value:

Python
def on_name_change():
    st.session_state.greeting = f"Hello, {st.session_state.name_box.title()}!"

st.text_input("Name", key="name_box", on_change=on_name_change)
st.write(st.session_state.get("greeting", ""))

Typing "ada lovelace" and pressing Enter shows "Hello, Ada Lovelace!". A form's submit button also accepts on_click.

Seeing the order (stand-in)

The block below is not Streamlit. It logs the sequence of events so you can see that the callback finishes before the script starts.

Python Stand-in: callbacks run before the script

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.

Forms and callbacks together

A form's form_submit_button(on_click=...) calls your function with the form's values already stored (read them with keys in st.session_state). It is a neat way to do "validate, save to a database, clear the form" in one place:

Python
def save_entry():
    entry = st.session_state.entry_text.strip()
    if entry:
        st.session_state.entries.append(entry)
        st.session_state.entry_text = ""         # clear the box

if "entries" not in st.session_state:
    st.session_state.entries = []

with st.form("add"):
    st.text_input("New item", key="entry_text")
    st.form_submit_button("Add", on_click=save_entry)

st.write(st.session_state.entries)

The page shows a text box and an "Add" button and an empty list []. Type "milk", press Add: the list shows ['milk'] and the text box is empty again. (Changing a widget's own state in a callback is allowed; doing it after the widget is created in the main script body is not.)

Common mistakes

  • Forgetting the submit button. A form without form_submit_button raises an error.
  • Reading the value outside the form too early. Variables like name always exist in the script, but they contain the last submitted values (the defaults until the first submit).
  • Calling st.button inside a form. Use st.form_submit_button.
  • Doing slow work in a callback. The callback blocks the rerun; use the script (with a spinner) for slow tasks.
  • Using st.write in a callback. The element is drawn at the top of the page before the rerun and then disappears; set state in callbacks and draw in the script.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does st.form change about widget behavior?

    A form buffers widget changes in the browser and sends them all together when the submit button is clicked.
  2. 2. In what order do callback and script run?

    Callbacks execute first; then Streamlit reruns the script from the top.
  3. 3. Which button must be used inside a form?

    Every form needs a form_submit_button; regular buttons are not allowed inside.
  4. 4. What does clear_on_submit=True do?

    It is handy for entry forms where the user adds one record after another.
  5. 5. How do you pass arguments to a callback?

    on_click=fn, args=(5,), kwargs={'step': 1}. Writing on_click=fn(5) would call it immediately.

Summary

  • st.form groups widgets and sends their values together when the user submits; it needs one form_submit_button.
  • Use forms to avoid needless reruns and to protect expensive work.
  • Callbacks (on_click, on_change) run before the script reruns; pass arguments with args and kwargs.
  • Change state in callbacks and draw in the script body.

Next: Columns and Containers