SelectBox/Radio: The index of the preselected option on first render

Is there any example code that would show how the index parameter of SelectBox or Radio is to be used correctly?

SelectBox and Radio, both offer an “index” parameter, and according to the documentation that will only be used for the “first render”.

It sounds like you could use it to initialize the selection with the last active selection stored in a database.

But it looks like that index parameter isn’t just read for the first render but for all subsequent once. So I thought I could use the SessionState to always keep track of the last selection and pass it to SelectBox or Radio via the index parameter on every subsequent render … but that doesn’t seem to work either, because for some reason when you select a different radio button, it only works on the 2nd click, the first one gets ignored and the selection jumps back to the previously selected one.

So I either use it the wrong way, which I hope, or that index parameter of SelectBox and Radio button never really worked, and can’t be used for anything meaningful.

Thanks in advance for any help,
–Marcel

Hello @mneuh,

Perhaps widgets use some sort of caching. If you update one argument, the widget renders again.
I don’t know if it is the intended behavior though. I haven’t checked that internal part of streamlit, so I may be wrong.

Running this line is sufficient to illustrate the issue:

st.radio("Choose a number.", list(range(20)), random.randint(0, 19))

However, with some tweaking of the SessionState, I managed to fix the value rollback issue here by running the app twice on session state update: Multi-page app with session state.

In the demo, there is a use-case with radio and selectbox widgets.

I hope it helps!

That seemed to have helped to solve my specific issue with radio buttons and multiple pages … no more jumping to previously selected radio buttons … very cool and very nice source code … thanks Synode!

Still curious what that “index” parameter in radio button and SelectBox should be used for.

1 Like