Skip to content

Instantly share code, notes, and snippets.

@asehmi
Created December 12, 2022 18:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asehmi/f3c76dae68a877138cf9b7307ddebdf7 to your computer and use it in GitHub Desktop.
Save asehmi/f3c76dae68a877138cf9b7307ddebdf7 to your computer and use it in GitHub Desktop.
Using callbacks and session state in Streamlit forms
import streamlit as st
import pandas as pd
import numpy as np
st.write('`Simple form callback demo`')
st.subheader('Constraints Solver')
state = st.session_state
if 'is_modified' not in state:
state['is_modified'] = False
if 'message' not in state:
state['message'] = 'No changes'
messageboard = st.empty()
def _change_callback():
settings = [state.setting_1, state.setting_2, state.setting_3]
print(settings)
is_modified = True in settings
state.is_modified = is_modified
state.message = 'Changes: {}'.format(settings) if is_modified else 'No changes'
print(state.message)
messageboard.info(state.message)
st.markdown('#### Settings')
with st.form('settings_form'):
st.checkbox(label='Setting 1', value=False, key='setting_1')
st.checkbox(label='Setting 2', value=False, key='setting_2')
st.checkbox(label='Setting 3', value=False, key='setting_3')
st.form_submit_button('Apply constraint settings', on_click=_change_callback)
if state.is_modified:
st.markdown('#### Results')
tab1, tab2 = st.tabs(["Charts","Data tables"])
settings = {k:np.random.rand(1,5)[0] for k,v in state.items() if 'setting_' in k and v == True}
settings_df = pd.DataFrame.from_dict(settings)
with tab1:
st.area_chart(settings_df)
with tab2:
st.write(settings_df)
else:
st.write('Please apply one or more constraints in the form above to see outcomes...')
@asehmi
Copy link
Author

asehmi commented Dec 12, 2022

simple-form-callback-demo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment