Hi! I’m trying to have page elements in an iterable display element by element until a user is done. I’ve implemented this with a recursive function, that I’ve simplified here:
def write_i(i):
st.write(i)
if i == 5:
return
if st.button('Next?', key=i):
i += 1
write_i(i)
If I call write_I(0), I’d expect 0 to print and the button ‘Next?’ to appear then, on clicking, for 1 to appear and the button, and so on until 5 is printed.
It seems to work for the first two iterations: I see 0, Next? then '1, Next?` – but on clicking that ‘Next’ button, the page starts again at 0.
Hi @paulwcoles, welcome to the Streamlit community!
This isn’t a bug per se, but a reflection of how the Streamlit evaluation model works. I’ve briefly written about that design decision here:
What is happening is that within your recursive function, you are calling a Streamlit widget (st.button), which is then re-running Streamlit from the top of your script. So instead of getting the behavior you are expecting, you are seeing the code be re-run and the state being lost.
As part of our 2021 roadmap, we’re working on a robust state management functionality, but in the meantime, you can take a look at the following example about maintaining state between runs. If you persist your variable i in state across runs, I think you should get the behavior you are looking for.
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.