Can not increase value when push the button in Streamlit

Viewed 477

My problem is when I initialize a new variable called self.items = 0, I would like to increase by 1 every time I imported value completely. But I try to debug with that variable, but it was always set by 0 as initialize

Here is my sample code:

import streamlit as st

class main:
    def __init__(self):
        self.items = 0
        self.run()

    def run(self):
        st.title('Home')
        print(self.items)
        if st.button('Submit'):
            self.items = self.items + 1
        print(self.items)

if __name__ == "__main__":
    main()
1 Answers

You're right, because the script re-runs every time you press the button, the variable is reinitialized to 0 and the counter won't work.

But there is a solution: st.session_state which was introduced in streamlit=0.84.0.
From the docs:

Session State is a way to share variables between reruns, for each user session.

Updating the code as following will work:

import streamlit as st


class main:
    def __init__(self):
        # Initialize a session state variable
        if "items" not in st.session_state:
            st.session_state["items"] = 0
        self.items = st.session_state["items"]
        self.run()

    def run(self):
        st.title("Home")
        if st.button("Submit"):
            st.session_state["items"] = st.session_state["items"] + 1
        print(self.items)


if __name__ == "__main__":
    main()

More about how this can be useful on this blog post.

Related