"Bad message format : i[o] is undefined" error with two containers

Summary

I have two containers in an app. The first container has a button. When user clicks the button, the second container should show a message. But I get this error:

Bad message format
i[o] is undefined

Steps to reproduce

Code snippet:

import streamlit as st

st.title('Test Page')

# first container
c1 = st.container()

# second container
c2 = st.container()

def show_msg():
    c2.write('You clicked Hello!')

c1.button(label='Hello', on_click=show_msg)

Debug info

  • Streamlit version: Streamlit, version 1.18.1
  • Python version: Python 3.10.9
  • Using Conda
  • OS version: Ubuntu 22.04
  • Browser version: Firefox 110.0

Additional Info:

It works if c2 is defined before c1, but the message appears before the button.

Hi @souravzzz,

Welcome to the Streamlit forum! :wave: :balloon:

I went digging through our GitHub issues to find similar issues:

Paraphrasing Ken’s comments on some issues: This is unintuitive behavior. A part of me thinks this is expected behavior (with a bad error message). Callbacks were designed to manipulate session state and not change the display of the app. Essentially, callbacks are called before the script runs, so while the variables c1 and c2 are defined, the containers do not currently exist (until the script run and is recreated again).

The solution is to not use callbacks for this use-case. Instead use a simple conditional to check if the button was clicked and, if so, call show_msg():

import streamlit as st

def show_msg():
    c2.write("You clicked Hello!")

st.title("Test Page")

# first container
c1 = st.container()

# second container
c2 = st.container()

if c1.button(label="Hello"):
    show_msg()

image

If you make the above change, you should no longer run into the error. If you feel none of the above linked issues adequately captures this issue, you’re welcome to submit a bug report in the Streamlit repo. Note: your bug report may be closed as a duplicate of one of the above issues.

1 Like

Thanks @snehankekre for the explanation. I ended up updating the session state through the button callback and check the status in the script to call the show_msg() function.

1 Like

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.