简体   繁体   中英

How to replace displayed value on a button click on streamlit

I am displaying a number "1" with streamlit. I would like to REPLACE this "1" with a "2" if I click "Perform calculation 2", and with a "3" if I click "Perform calculation 3". It kind of works but I do not want to display both a the same time, I would like to replace the "1" with either "2" or "3" depending on the button I click.

import streamlit as st

st.write("1")

runButton = st.button("Perform calculation 2")
if runButton:
    st.write("2")

runButton2 = st.button("Perform calculation 3")
if runButton2:
    st.write("3")

在此处输入图像描述

You can use a session state and a callback to the button.

Code

import streamlit as st

if 'num' not in st.session_state:
    st.session_state.num = "1"

def update2():
    st.session_state.num = "2"

def update3():
    st.session_state.num = "3"

st.write(st.session_state.num)
st.button("Perform calculation 2", on_click=update2, key='key_2')
st.button("Perform calculation 3", on_click=update3, key='key_3')

Output

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM