Placing the st.button below the st.number_input in Streamlit

Summary

How can i place my st.button under the st.number_input while maintaining the same functionality

Steps to reproduce

Example:

Code snippet:

keys = ['pigm_bayfer_brown_645_t', 'pigm_bayfer_yellow_420']
for key in keys:
        if key not in st.session_state:
            st.session_state[key] = 0.0

if st.button('Reset'):
   for key in keys:
         st.session_state[key] = 0.0

pigm_bayfer_brown_645_t = st.number_input('Bayferrox braun 645T [kg]:', min_value=0.0, max_value=1.0,step=0.00001, format='%.7f', key="pigm_bayfer_brown_645_t")

pigm_bayfer_yellow_420 = st.number_input('Bayferrox gelb 420 [kg]:', min_value=0.0,    max_value=1.0,step=0.00001, format='%.7f', key="pigm_bayfer_yellow_420")

If applicable, please provide the steps we should take to reproduce the error or specified behavior.

Expected behavior:

I want to place the Reset Button below the st.number_input, so that I can easily reset every entry to 0.0 by simply clicking the Reset Button.

Actual behavior:

If i place the st.button(“Reset”) below the st.number_input this error gets triggered:
StreamlitAPIException : st.session_state.pigm_bayfer_brown_645_t cannot be modified after the widget with key pigm_bayfer_brown_645_t is instantiated.

Is it even possible to place it below the st.number_input?

If you need to display items in a different order than they appear within your script, use containers. The order in which you instantiate containers determines where those containers are on the page. You can then write into those containers in reverse order if needed.

import streamlit as st

a = st.container()
b = st.container()

b.write('This will appear as the second line since it is in the second container.')
a.write('This will appear as the first line since it is in the first container.')

Alternatively, you can use a callback function attached to the button to execute your resetting code instead of doing it inline after the button.

def reset(keys):
    for key in keys:
        st.session_state[key] = 0.0

st.button('Reset', on_click=reset, args=[keys]):

Hello @mathcatsand,

Thank u very much, this helped a lot :).

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.