How recreate widget with default value

I know that widgets are stateful but when i am explicitly recreating a widget with a specific default value it does not work. is there any way.

import streamlit as st

options = [“List”,“add”,“Edit”,“Delete”]

#create menu

def gen_menu(value):
x = st.pills(“Options”,options,default = value)

return x

sel_def = “List”
selection = gen_menu(sel_def)

st.write(f"selection is:- {selection}")
if selection == “add”:

name = st.selectbox(“add new”,options = [1,2,3])

if st.button(“submit”):
st.write(selection)
st.rerun()

the page is generated with the same “add” selected after pressing submit on “add” logic. even though I am calling the function with new value after rerun. What is going wrong here?

Hi @pixelfire

I guess you want to pass a value in the gen_menu function and have it preselected when the code is run, right? Have a look if the following code addresses the issue:

import streamlit as st

name = ''
def gen_menu(value): return st.pills('Options', ('List','Add','Edit','Delete'), default = value)  #create menu

selection = gen_menu('List')
st.write(f"selection is:- {selection}")
if selection == 'Add': name = st.selectbox('add new', options = [1,2,3])

if st.button('submit'): st.write(f"{selection} {name}")

If you replace

selection = gen_menu('List')

with

selection = gen_menu('Add')

it should work too.

Cheers

thank sir. my idea is that after ‘add’ is completed successfully , i will do st.rerun() and the menu should return to ‘list’ as default . however with the code you just provided , it stays at the same ‘add’ selection after i click on submit on ‘add’. i tried this here.

Hi @pixelfire

I misunderstood what you wanted. Please check if the following code works for you:

import streamlit as st
from streamlit import session_state as ss

if 'default_menu_option' not in ss: ss.default_menu_option = ['List', 'List']
my_options = ('List','Add','Edit','Delete')

def callback(vkey): ss.default_menu_option[1] = ss[vkey]
ss.default_menu_option[0] = st.pills('Options', 
                                    my_options, 
                                    default=ss.default_menu_option[1],
                                    key='dm',
                                    args=('dm',),
                                    on_change=callback)  #create menu

if ss.default_menu_option[0] == 'Add': 
  name = st.selectbox('add new', options = [1,2,3], index=None)
  if name != None:
    #  do some thing here...
    pass

if st.button('submit'): 
  ss.default_menu_option[1] = 'List'
  st.rerun()

Cheers