pypi-streamlit

Description
The fastest way to build and share data apps
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/pypi-streamlit@1.16.0

layout-containers.md docs/

1
# Layout and Containers
2
3
Functions for organizing content and creating sophisticated multi-panel layouts. These containers help structure your Streamlit application by grouping related content, creating responsive layouts, and managing form submissions.
4
5
## Capabilities
6
7
### Basic Containers
8
9
Fundamental container types for organizing and grouping content.
10
11
```python { .api }
12
def container() -> DeltaGenerator:
13
"""
14
Create an invisible container for grouping elements.
15
16
Returns:
17
DeltaGenerator: Container object for adding elements
18
"""
19
20
def empty() -> DeltaGenerator:
21
"""
22
Create a placeholder container that can be filled later.
23
24
Returns:
25
DeltaGenerator: Empty container that can be populated programmatically
26
"""
27
```
28
29
#### Usage Example
30
31
```python
32
import streamlit as st
33
34
# Container for grouping related content
35
with st.container():
36
st.write("This content is in a container")
37
st.button("Container button")
38
39
# Empty placeholder that can be filled later
40
placeholder = st.empty()
41
42
# Later in the code, fill the placeholder
43
placeholder.text("This text was added to the placeholder!")
44
```
45
46
### Column Layouts
47
48
Create responsive multi-column layouts for side-by-side content arrangement.
49
50
```python { .api }
51
def columns(spec, gap: str = "small") -> List[DeltaGenerator]:
52
"""
53
Create a set of columns for side-by-side layout.
54
55
Parameters:
56
- spec: Number of columns (int) or list of column widths
57
- gap: Gap size between columns ("small", "medium", "large")
58
59
Returns:
60
List[DeltaGenerator]: List of column containers
61
"""
62
```
63
64
#### Usage Example
65
66
```python
67
import streamlit as st
68
69
# Equal width columns
70
col1, col2, col3 = st.columns(3)
71
72
with col1:
73
st.header("Column 1")
74
st.write("Content for first column")
75
76
with col2:
77
st.header("Column 2")
78
st.write("Content for second column")
79
80
with col3:
81
st.header("Column 3")
82
st.write("Content for third column")
83
84
# Custom width columns (ratios)
85
left_col, middle_col, right_col = st.columns([1, 2, 1])
86
87
with left_col:
88
st.write("Narrow left")
89
90
with middle_col:
91
st.write("Wide middle column")
92
93
with right_col:
94
st.write("Narrow right")
95
96
# Large gap between columns
97
col_a, col_b = st.columns(2, gap="large")
98
99
with col_a:
100
st.metric("Revenue", "$1.2M")
101
102
with col_b:
103
st.metric("Users", "1,234")
104
```
105
106
### Tabbed Interface
107
108
Create tabbed interfaces for organizing content into separate views.
109
110
```python { .api }
111
def tabs(tab_labels: List[str]) -> List[DeltaGenerator]:
112
"""
113
Create a tabbed interface.
114
115
Parameters:
116
- tab_labels: List of tab names/labels
117
118
Returns:
119
List[DeltaGenerator]: List of tab containers
120
"""
121
```
122
123
#### Usage Example
124
125
```python
126
import streamlit as st
127
import pandas as pd
128
import numpy as np
129
130
# Create tabs
131
tab1, tab2, tab3 = st.tabs(["Data", "Charts", "Settings"])
132
133
with tab1:
134
st.header("Data View")
135
data = pd.DataFrame(np.random.randn(10, 3), columns=["A", "B", "C"])
136
st.dataframe(data)
137
138
with tab2:
139
st.header("Charts View")
140
st.line_chart(data)
141
st.bar_chart(data)
142
143
with tab3:
144
st.header("Settings")
145
st.selectbox("Theme", ["Light", "Dark"])
146
st.checkbox("Enable notifications")
147
```
148
149
### Expandable Sections
150
151
Create collapsible sections to organize content hierarchically.
152
153
```python { .api }
154
def expander(label: str, expanded: bool = False) -> DeltaGenerator:
155
"""
156
Create an expandable/collapsible container.
157
158
Parameters:
159
- label: Text displayed on the expander header
160
- expanded: Whether the expander is initially expanded
161
162
Returns:
163
DeltaGenerator: Expandable container
164
"""
165
```
166
167
#### Usage Example
168
169
```python
170
import streamlit as st
171
172
# Basic expander
173
with st.expander("See explanation"):
174
st.write("""
175
This is a detailed explanation that is hidden by default.
176
Users can click to expand and see this content.
177
""")
178
179
# Initially expanded expander
180
with st.expander("Configuration Options", expanded=True):
181
st.slider("Temperature", 0, 100, 50)
182
st.selectbox("Model", ["GPT-3", "GPT-4"])
183
184
# Multiple expanders for organized content
185
with st.expander("📊 Data Analysis"):
186
st.write("Data analysis content here")
187
st.line_chart([1, 2, 3, 4, 5])
188
189
with st.expander("🔧 Settings"):
190
st.checkbox("Debug mode")
191
st.number_input("Batch size", value=32)
192
193
with st.expander("ℹ️ Help & Documentation"):
194
st.markdown("""
195
## Getting Started
196
1. Upload your data
197
2. Configure parameters
198
3. Run analysis
199
""")
200
```
201
202
### Sidebar
203
204
Special container for sidebar content (accessed via `st.sidebar`).
205
206
```python { .api }
207
sidebar: DeltaGenerator
208
# Access sidebar through st.sidebar
209
# All regular widgets and containers work in sidebar context
210
```
211
212
#### Usage Example
213
214
```python
215
import streamlit as st
216
217
# Sidebar content
218
st.sidebar.title("Navigation")
219
page = st.sidebar.selectbox("Choose page:", ["Home", "Data", "Results"])
220
221
st.sidebar.markdown("---")
222
st.sidebar.write("Settings")
223
debug_mode = st.sidebar.checkbox("Debug mode")
224
batch_size = st.sidebar.slider("Batch size", 1, 100, 32)
225
226
# Sidebar with sections
227
with st.sidebar:
228
st.markdown("### Filters")
229
230
category = st.selectbox("Category:", ["All", "A", "B", "C"])
231
date_range = st.date_input("Date range:")
232
233
st.markdown("### Options")
234
show_raw_data = st.checkbox("Show raw data")
235
export_format = st.radio("Export format:", ["CSV", "JSON"])
236
237
# Main content area
238
st.title(f"Current page: {page}")
239
if debug_mode:
240
st.write(f"Debug: Batch size is {batch_size}")
241
```
242
243
### Forms
244
245
Group related inputs and control when they trigger app reruns.
246
247
```python { .api }
248
def form(key: str, clear_on_submit: bool = False) -> DeltaGenerator:
249
"""
250
Create a form container to batch widget interactions.
251
252
Parameters:
253
- key: Unique key for the form
254
- clear_on_submit: Whether to clear form inputs after submission
255
256
Returns:
257
DeltaGenerator: Form container
258
"""
259
260
def form_submit_button(label: str = "Submit", help: str = None, on_click=None, args=None, kwargs=None, type: str = "primary", disabled: bool = False, use_container_width: bool = False) -> bool:
261
"""
262
Display a form submit button (must be used inside a form).
263
264
Parameters:
265
- label: Text displayed on the submit button
266
- help: Tooltip text shown on hover
267
- on_click: Callback function executed on submit
268
- args: Arguments passed to callback function
269
- kwargs: Keyword arguments passed to callback function
270
- type: Button type ("primary" or "secondary")
271
- disabled: Whether the button is disabled
272
- use_container_width: Whether to use full container width
273
274
Returns:
275
bool: True if submit button was clicked, False otherwise
276
"""
277
```
278
279
#### Usage Example
280
281
```python
282
import streamlit as st
283
284
# Simple form
285
with st.form("my_form"):
286
st.write("User Information")
287
name = st.text_input("Name")
288
age = st.number_input("Age", min_value=0, max_value=120)
289
email = st.text_input("Email")
290
291
# Form submission
292
submitted = st.form_submit_button("Submit")
293
294
if submitted:
295
st.success(f"Form submitted for {name}, age {age}, email {email}")
296
297
# Form with sections and validation
298
with st.form("contact_form", clear_on_submit=True):
299
st.markdown("### Contact Information")
300
301
col1, col2 = st.columns(2)
302
with col1:
303
first_name = st.text_input("First Name")
304
phone = st.text_input("Phone")
305
with col2:
306
last_name = st.text_input("Last Name")
307
email = st.text_input("Email")
308
309
st.markdown("### Message")
310
subject = st.selectbox("Subject", ["General Inquiry", "Support", "Feedback"])
311
message = st.text_area("Message", height=100)
312
313
# Submit with validation
314
if st.form_submit_button("Send Message"):
315
if first_name and last_name and email and message:
316
st.success("Message sent successfully!")
317
st.balloons()
318
else:
319
st.error("Please fill in all required fields")
320
321
# Form with custom submit handling
322
def handle_submission():
323
st.session_state.form_submitted = True
324
325
with st.form("custom_form"):
326
data = st.text_input("Enter data:")
327
328
submitted = st.form_submit_button(
329
"Process Data",
330
on_click=handle_submission
331
)
332
333
if submitted and st.session_state.get("form_submitted", False):
334
st.write(f"Processing: {data}")
335
st.session_state.form_submitted = False
336
```
337
338
### Advanced Layout Patterns
339
340
Combine containers for sophisticated layouts.
341
342
#### Usage Example
343
344
```python
345
import streamlit as st
346
347
# Header section
348
header_container = st.container()
349
with header_container:
350
st.title("Dashboard")
351
col1, col2, col3 = st.columns(3)
352
with col1:
353
st.metric("Total Users", "1,234", "+5%")
354
with col2:
355
st.metric("Revenue", "$12.3K", "+12%")
356
with col3:
357
st.metric("Growth", "8.2%", "+1.2%")
358
359
# Main content with sidebar navigation
360
with st.sidebar:
361
st.selectbox("Time Period", ["Last 7 days", "Last 30 days", "Last 90 days"])
362
st.multiselect("Filters", ["Region A", "Region B", "Region C"])
363
364
# Tabbed main content
365
tab1, tab2 = st.tabs(["Overview", "Details"])
366
367
with tab1:
368
# Overview content with expandable sections
369
with st.expander("Charts", expanded=True):
370
col1, col2 = st.columns(2)
371
with col1:
372
st.line_chart([1, 3, 2, 4, 5])
373
with col2:
374
st.bar_chart([2, 1, 3, 4, 2])
375
376
with st.expander("Data Table"):
377
st.dataframe({"A": [1, 2, 3], "B": [4, 5, 6]})
378
379
with tab2:
380
# Details content
381
st.write("Detailed view content here")
382
383
# Footer placeholder
384
footer = st.empty()
385
footer.markdown("---")
386
footer.caption("Last updated: 2024-01-01")
387
```
388
389
## Layout Best Practices
390
391
- Use **columns** for side-by-side content
392
- Use **tabs** for different views of the same data
393
- Use **expanders** for optional/detailed information
394
- Use **forms** to batch related inputs and reduce reruns
395
- Use **sidebar** for navigation and persistent controls
396
- Use **containers** to group related elements logically