插入一个多元素容器。

在你的应用程序中插入一个不可见的容器,可以用来容纳多个元素。这允许你,例如,无序地插入多个元素到你的应用程序中。

要向返回的容器添加元素,您可以使用with表示法(推荐)或直接在返回的对象上调用方法。请参见下面的示例。

函数签名[source]

st.container(*, height=None, border=None, key=None)

参数

height (int or None)

容器的期望高度,以像素表示。如果为None(默认值),容器将根据其内容自动调整大小。如果设置了固定高度,对于较大的内容将启用滚动,并在容器周围显示灰色边框,以视觉上将其滚动表面与应用程序的其余部分分开。

注意

请谨慎使用带有滚动的容器。如果使用,尽量保持高度较小(低于500像素)。否则,在移动设备上,容器的滚动表面可能会覆盖屏幕的大部分区域,这使得滚动应用程序的其余部分变得困难。

border (bool or None)

是否在容器周围显示边框。如果为None(默认值),当容器设置为固定高度时显示边框,否则不显示。

key (str or None)

一个可选的字符串,用于为此容器提供稳定的身份。

此外,如果提供了key,它将被用作CSS类名前缀,前缀为st-key-

示例

使用with符号插入元素:

import streamlit as st

with st.container():
    st.write("This is inside the container")

    # You can call any Streamlit command, including custom components:
    st.bar_chart(np.random.randn(50, 3))

st.write("This is outside the container")

无序插入元素:

import streamlit as st

container = st.container(border=True)
container.write("This is inside the container")
st.write("This is outside the container")

# Now insert some more in the container
container.write("This is inside too")

使用 height 来制作网格:

import streamlit as st

row1 = st.columns(3)
row2 = st.columns(3)

for col in row1 + row2:
    tile = col.container(height=120)
    tile.title(":balloon:")

使用 height 为长内容创建一个滚动容器:

import streamlit as st

long_text = "Lorem ipsum. " * 1000

with st.container(height=300):
    st.markdown(long_text)
forum

还有问题吗?

我们的 论坛 充满了有用的信息和Streamlit专家。