I tried to use buttons to store and load input values.The code is as follows:
import streamlit as st
import pickle
Load session state from local file
if st.button(“Load session state”):
with open(“saved_dictionary.pkl”, “rb”) as f:
session_state = pickle.load(f)
st.session_state.update(session_state)
import streamlit as st
import pickle
# Load session state from local file
if st.button("Load session state"):
with open("saved_dictionary.pkl", "rb") as f:
session_state = pickle.load(f)
st.session_state.update(session_state)
col1, col2, col3 = st.columns(3)
with col1:
num1 = st.text_input("num1", key="num1")
with col2:
num2 = st.text_input("num2", key="num2")
with col3:
try:
st.write("")
st.write("")
st.write("Sum: ", int(num1) + int(num2))
except:
st.write("")
st.write("")
st.write("Error")
# Save session_state to local file
if st.button("Submit session state"):
with open("saved_dictionary.pkl", "wb") as f:
pickle.dump(dict(st.session_state), f)
st.write("num1: ", num1)
st.write("num2: ", num2)
You can try this example. It uses a form to get user input and display result. Also Pickled data is read to pandas dataframe to easily manipulate it. It also uses a callback in the form button.
import streamlit as st
from streamlit import session_state as ss
import pickle
import pandas as pd
from datetime import datetime
DATA_FILE = 'data.pkl'
def save_data(file_name, value1, value2):
try:
with open(file_name, 'rb') as file:
data = pickle.load(file)
except (FileNotFoundError, EOFError):
data = []
data.append({'value1': value1, 'value2': value2, 'timestamp': datetime.now()})
with open(file_name, 'wb') as file:
pickle.dump(data, file)
def load_data(file_name):
try:
with open(file_name, 'rb') as file:
data = pickle.load(file)
return pd.DataFrame(data)
except (FileNotFoundError, EOFError):
return pd.DataFrame()
def sum_cb():
ss.sum = str(int(ss.num1) + int(ss.num2))
save_data(DATA_FILE, ss.num1, ss.num2)
with st.form('form', clear_on_submit=False):
col1, col2, col3 = st.columns(3)
with col1:
st.text_input("num1", key="num1")
with col2:
st.text_input("num2", key="num2")
with col3:
st.text_input("sum", key="sum", disabled=True)
st.form_submit_button('Get Result', on_click=sum_cb)
st.markdown('# Current Data')
df = load_data(DATA_FILE)
st.dataframe(df, use_container_width=True)
st.form is so cool! It solved my problem perfectly!Thank you!
import streamlit as st
from streamlit import session_state as ss
import pickle
import pandas as pd
from datetime import datetime
def save_data(file_name, value1, value2):
try:
with open(file_name, 'rb') as file:
data = pickle.load(file)
except (FileNotFoundError, EOFError):
data = []
data.append({'value1': value1, 'value2': value2, 'timestamp': datetime.now()})
with open(file_name, 'wb') as file:
pickle.dump(data, file)
def load_data(file_name):
try:
with open(file_name, 'rb') as file:
data = pickle.load(file)
return pd.DataFrame(data)
except (FileNotFoundError, EOFError):
return pd.DataFrame()
# Don't need reinput data when refresh page!
df = load_data('data.pkl')
pre_value1 = df['value1'].iloc[-1] if len(df) > 0 else ''
pre_value2 = df['value2'].iloc[-1] if len(df) > 0 else ''
pre_timestamp = df['timestamp'].iloc[-1] if len(df) > 0 else ''
st.code(f'Last time updated: {pre_timestamp}, num1: {pre_value1}, num2: {pre_value2}')
# Load data from old session
ss.num1 = st.session_state.num1 if 'num1' in st.session_state else pre_value1
ss.num2 = st.session_state.num2 if 'num2' in st.session_state else pre_value2
def sum_cb():
ss.sum = str(int(ss.num1) + int(ss.num2))
save_data('data.pkl', ss.num1, ss.num2)
# If I don't click the button, the value will be the last time I input
with st.form('form', clear_on_submit=False):
col1, col2, col3 = st.columns(3)
with col1:
st.text_input("num1", key="num1")
with col2:
st.text_input("num2", key="num2")
with col3:
st.text_input("sum", key="sum", disabled=True)
st.form_submit_button('Get Result', on_click=sum_cb)
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.