In streamlit I have a display issue using a text_input.
I want, with a text_input, to display a path stored in a .yaml file, and if changed in the text field in the app, to be updated in the yaml file.
For what I’m doing, I want this option to be available in 2 different pages.
For the example, I have three pages:
- A main page to start the app – that’s an empty page, but it is used to start the app with python (streamlit run Main_page.py)
- 2 pages (page1 and page2) to show the problem.
The code in page1 and 2 is the same, and is displayed below.
The steps are:
- Loading the content of the yaml file
- Creating the “test” key in the session_state if it does not exists
- Defining the callback function that check if the content of the yaml file is similar to the content of the sessions_state. If not, update the content of the yaml file, and save it.
- Creating the text_input, with the callbacl function and the test key.
import streamlit as st import yaml from pathlib import Path # Read the yaml file, and load the content path_to_yaml= Path.cwd().parent / "path.yaml" contents = path_to_yaml.read_text() yaml_content = yaml.safe_load(contents) # Check if the test field is available in the session_state if "test" not in st.session_state: st.session_state['test']=yaml_content["test"] # Callback function when changing the value of the text field def on_change(): # Update the yaml file if different from the session_state if Path(yaml_content['test'])!=Path(st.session_state.test): yaml_content['test']=str(st.session_state.test) path_to_yaml.write_text(yaml.dump(yaml_content)) # Call the text_input function with the callback function and the "test" key st.text_input( "Folder location to the parent file ", on_change=on_change(), key="test")
After the command streamlit run Main_page.py is run, the app opens on the Main_page, then I click on the page1, and the text_input works fine with the correct value showing. Changing the value of the text input works as expected – the yaml file is correctly updated (show the screenshot below for visualization).
Now if I click on page2, the text_input is displaying nothing. If I go back on page1, the text_input shows nothing neither:
But if I click on the Main_page, then on page1 (or page2), then the text_input displays the correct value again…
In page1.py and page2.py, I changed the text_input command
st.text_input( "Folder location to the parent file ", on_change=on_change(), key="test")
st.text_input( "Folder location to the parent file ", value=st.session_state.test, on_change=on_change(), key="test")