Changing the display element later

Summary

Hi, I am new to streamit. A small question is I need to display a value that changes when a button is clicked. Lets say I have a caption/header etc that needs to be changed when I click a button. is this possible?

Steps to reproduce

import streamlit as st
import pandas as pd
import numpy as np

st.title(“Sample Tutorial for adding numbers”)

col1, col2 = st.columns(2)

with col1:

a = st.text_input("Please enter number 1",key = "number 1" , help = "Enter the first number")
b = st.text_input("Please enter number 2",key = "number 2" , help = "Enter the second number")
# sum_value = st.metric(value = 1, label = "sum")
#
sum = st.button("Calculate Sum", key = "calculate")
sum_caption = st.caption("The sum is:")

if sum:

try:
    a = float(a)
    b = float(b)
    c = a + b
    st.write(c)
except:
        st.exception("One of the numbers entered is not float")

I’m not 100% sure how you want to modify your code as it seems to work when I use it, but you can create st.empty() containers and then update these such as in the code below

import streamlit as st
import pandas as pd
import numpy as np

st.title("Sample Tutorial for adding numbers")

col1, col2 = st.columns(2)
sum_caption = st.empty()
sum_caption.caption("The sum is:")
mycaption = st.empty()
with col1:
    a = st.text_input("Please enter number 1",key = "number 1" , help = "Enter the first number")
    b = st.text_input("Please enter number 2",key = "number 2" , help = "Enter the second number")
    # sum_value = st.metric(value = 1, label = "sum")
    #
    mysum = st.button("Calculate Sum", key = "calculate")
 
    if mysum:
        try:
            a = float(a)
            b = float(b)
            c = a + b
            mycaption.caption(c)
        except:
                st.exception("One of the numbers entered is not float")
1 Like

Hi Luke. Thanks a lot for the answer. I was able to find it online the same answer and it worked. Nonetheless I think that it would be much easier if we are able to access the value of widget later and change it if possible. What do you think?

Hi, sorry, I’m not 100% sure what you mean.
You would like to access the input numbers later?
You can so that with st.sessionstate

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