Navigating through a list

A simple question but I couldn’t find the answer anywhere. Probably solved quickly if you know Streamlit:

I want to work on a list of images. For every image I need to do some operations on screen through the Streamlit app, then click on the Next button and proceed with the next image.

But I just can’t setup my next/previous navigation through the list with buttons. When I click my Next button, the file_index increases as expected, but a following attempt to click the Next button doesn’t have any effect.

I think it’s the way Streamlit automatically recalculates everything that has changes, and therefore also my initiating statement “file_index=0”. If I add other widgets to my app and click on them while running, the file_index=0 seems to executed as well. But I’m not sure how to tackle this. Should I tackle this using the cache settings?

Simplified code (no images, no operations, just the buttons and the displaying of the resulting item from the list:

import streamlit as st

file_index=0

file_list=[“Cat”,“Dog”,“Mouse”,“Snake”,“Tiger”]
image_count=len(file_list)

placeholder1 = st.empty()
placeholder2 = st.empty()
placeholder1.text(file_index)
placeholder2.text(file_list[file_index])

if st.sidebar.button(‘Previous’):
file_index=max(0,file_index-1)
placeholder1.text(file_index)
placeholder2.text(file_list[file_index])

if st.sidebar.button(‘Next’):
file_index=min(file_index+1,image_count)
placeholder1.text(file_index)
placeholder2.text(file_list[file_index])

Thanks for any helpful suggestion on how to navigate through a list without restarting at the begin!

Buttons just go true for the next run-through of the code.

You’ll need something stateful. There are some state hacks, though I’d recommend either:

Use a counter (streamlit number input)

Store your state in a database and have the page just refresh on a button click and load “next unprocessed image”.

1 Like

Thanks Ian,

Great, I think you’re referring to the two hacks (SessionState.py and st_state_patch.py) I found on https://docs.streamlit.io/en/latest/changelog.html? I tried st_state_patch.py and it works, so thanks!

I really think this should be in the regular Streamlit code, because nothing less than absolutely necessary in many cases.

Btw: are shortcut keys no idea for such a navigating app (in other words: wouldn’t it be nice if one can execute a screen button click by actually pressing a fysical keyboard button?

Just another idea for the Streamlit team. Keep up the good work over there!

1 Like