pypi-streamlit

Description
A faster way to build and share data apps
Author
tessl
Last updated

How to use

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

layout-containers.md docs/

1
# Layout and Containers
2
3
Layout management and container elements for organizing app structure and controlling element positioning. These components provide the foundation for creating well-structured, responsive Streamlit applications.
4
5
## Capabilities
6
7
### Column Layouts
8
9
Create multi-column layouts for side-by-side element placement.
10
11
```python { .api }
12
def columns(spec, gap="small"):
13
"""
14
Insert containers laid out as side-by-side columns.
15
16
Parameters:
17
- spec (int or sequence): Number of columns or sequence of column widths
18
- gap (str): Gap size between columns ('small', 'medium', 'large')
19
20
Returns:
21
list: List of column containers
22
"""
23
```
24
25
### Tab Layouts
26
27
Organize content into selectable tabs.
28
29
```python { .api }
30
def tabs(tab_labels):
31
"""
32
Insert containers separated into tabs.
33
34
Parameters:
35
- tab_labels (list): List of tab labels
36
37
Returns:
38
list: List of tab containers
39
"""
40
```
41
42
### Generic Containers
43
44
Multi-element containers for grouping related content.
45
46
```python { .api }
47
def container(height=None, border=False):
48
"""
49
Insert a multi-element container.
50
51
Parameters:
52
- height (int): Container height in pixels
53
- border (bool): Show container border
54
55
Returns:
56
DeltaGenerator: Container object
57
"""
58
59
def expander(label, expanded=False):
60
"""
61
Insert a multi-element container that can be expanded/collapsed.
62
63
Parameters:
64
- label (str): Expander label
65
- expanded (bool): Initial expanded state
66
67
Returns:
68
DeltaGenerator: Expander container object
69
"""
70
71
def popover(label, help=None, disabled=False, use_container_width=False, icon=None):
72
"""
73
Insert a popover container that appears on click.
74
75
Parameters:
76
- label (str): Popover trigger button label
77
- help (str): Optional tooltip text
78
- disabled (bool): Disable the popover trigger
79
- use_container_width (bool): Use full container width for trigger
80
- icon (str): Optional icon for trigger button
81
82
Returns:
83
DeltaGenerator: Popover container object
84
"""
85
```
86
87
### Sidebar
88
89
Dedicated sidebar area for navigation and controls.
90
91
```python { .api }
92
# Sidebar container object with all main interface methods
93
sidebar: DeltaGenerator
94
```
95
96
### Forms
97
98
Container for batching widget interactions and submissions.
99
100
```python { .api }
101
def form(key, clear_on_submit=False, border=True):
102
"""
103
Create a form that batches elements together with a submit button.
104
105
Parameters:
106
- key (str): Unique form identifier
107
- clear_on_submit (bool): Clear form values after submission
108
- border (bool): Show form border
109
110
Returns:
111
DeltaGenerator: Form container object
112
"""
113
114
def form_submit_button(label="Submit", help=None, on_click=None, args=None, kwargs=None, type="secondary", disabled=False, use_container_width=False, icon=None):
115
"""
116
Display a form submit button (only works inside st.form).
117
118
Parameters:
119
- label (str): Button label
120
- help (str): Optional tooltip text
121
- on_click (callable): Function to call when submitted
122
- args (tuple): Arguments to pass to on_click function
123
- kwargs (dict): Keyword arguments to pass to on_click function
124
- type (str): Button type ('primary' or 'secondary')
125
- disabled (bool): Disable the button
126
- use_container_width (bool): Use full container width
127
- icon (str): Optional icon name
128
129
Returns:
130
bool: True if form was submitted, False otherwise
131
"""
132
```
133
134
### Utility Containers
135
136
Special-purpose containers for specific layout needs.
137
138
```python { .api }
139
def empty():
140
"""
141
Insert a single-element container for placeholder content.
142
143
Returns:
144
DeltaGenerator: Empty container object
145
"""
146
147
def divider():
148
"""
149
Display a horizontal rule divider.
150
151
Returns:
152
None
153
"""
154
```
155
156
### Progress and Status Containers
157
158
Containers for displaying progress and status information.
159
160
```python { .api }
161
def progress(value, text=None):
162
"""
163
Display a progress bar.
164
165
Parameters:
166
- value (float): Progress value between 0.0 and 1.0
167
- text (str): Optional progress text
168
169
Returns:
170
DeltaGenerator: Progress bar object
171
"""
172
173
def status(label, expanded=False, state="running"):
174
"""
175
Display a status container to show progress of long-running tasks.
176
177
Parameters:
178
- label (str): Status label
179
- expanded (bool): Show contents by default
180
- state (str): Status state ('running', 'complete', 'error')
181
182
Returns:
183
DeltaGenerator: Status container object
184
"""
185
186
def spinner(text="In progress..."):
187
"""
188
Temporarily display a message with spinner while executing a block of code.
189
190
Parameters:
191
- text (str): Message to display
192
193
Returns:
194
ContextManager: Spinner context manager
195
"""
196
```
197
198
## Usage Examples
199
200
### Multi-Column Layouts
201
202
```python
203
import streamlit as st
204
205
# Equal-width columns
206
col1, col2, col3 = st.columns(3)
207
208
with col1:
209
st.header("Column 1")
210
st.write("Content for column 1")
211
st.button("Button 1")
212
213
with col2:
214
st.header("Column 2")
215
st.write("Content for column 2")
216
st.selectbox("Options", ["A", "B", "C"])
217
218
with col3:
219
st.header("Column 3")
220
st.write("Content for column 3")
221
st.slider("Value", 0, 100, 50)
222
223
# Custom column widths
224
col1, col2 = st.columns([2, 1]) # 2:1 ratio
225
226
with col1:
227
st.write("This column is twice as wide")
228
229
with col2:
230
st.write("Narrow column")
231
232
# Columns with different gaps
233
st.subheader("Large Gap Between Columns")
234
col1, col2 = st.columns(2, gap="large")
235
236
with col1:
237
st.info("Column with large gap")
238
239
with col2:
240
st.info("Another column")
241
```
242
243
### Tab Organization
244
245
```python
246
# Create tabs
247
tab1, tab2, tab3 = st.tabs(["πŸ“Š Charts", "πŸ“‹ Data", "βš™οΈ Settings"])
248
249
with tab1:
250
st.header("Charts Tab")
251
252
# Sample chart
253
import pandas as pd
254
import numpy as np
255
256
chart_data = pd.DataFrame(
257
np.random.randn(20, 3),
258
columns=['a', 'b', 'c']
259
)
260
st.line_chart(chart_data)
261
262
with tab2:
263
st.header("Data Tab")
264
st.dataframe(chart_data)
265
266
with tab3:
267
st.header("Settings Tab")
268
st.checkbox("Enable notifications")
269
st.selectbox("Theme", ["Light", "Dark", "Auto"])
270
```
271
272
### Expandable Content
273
274
```python
275
# Basic expander
276
with st.expander("See explanation"):
277
st.write("""
278
This is additional content that can be hidden or shown.
279
Perfect for detailed explanations, advanced options, or FAQ sections.
280
""")
281
st.code('''
282
def hello():
283
print("Hello, World!")
284
''')
285
286
# Expander with initial expanded state
287
with st.expander("Advanced Configuration", expanded=True):
288
st.slider("Advanced parameter 1", 0, 100, 50)
289
st.checkbox("Enable advanced feature")
290
st.text_input("Custom setting")
291
```
292
293
### Sidebar Usage
294
295
```python
296
# Add content to sidebar
297
st.sidebar.title("Navigation")
298
st.sidebar.markdown("Use the controls below:")
299
300
# Sidebar inputs
301
page = st.sidebar.selectbox(
302
"Choose a page:",
303
["Home", "Data Analysis", "Visualization", "Settings"]
304
)
305
306
if page == "Data Analysis":
307
# Sidebar filters for data analysis
308
st.sidebar.header("Filters")
309
310
date_range = st.sidebar.date_input(
311
"Select date range:",
312
value=[pd.Timestamp('2023-01-01'), pd.Timestamp('2023-12-31')]
313
)
314
315
categories = st.sidebar.multiselect(
316
"Select categories:",
317
["Category A", "Category B", "Category C"],
318
default=["Category A"]
319
)
320
321
# Main content based on sidebar selection
322
st.title(f"{page} Page")
323
st.write(f"Content for {page}")
324
```
325
326
### Form Containers
327
328
```python
329
# Contact form example
330
with st.form("contact_form"):
331
st.write("Contact Us")
332
333
name = st.text_input("Name *", placeholder="Enter your full name")
334
email = st.text_input("Email *", placeholder="your@email.com")
335
subject = st.selectbox("Subject", [
336
"General Inquiry",
337
"Technical Support",
338
"Bug Report",
339
"Feature Request"
340
])
341
message = st.text_area("Message *", placeholder="Enter your message here...")
342
343
# Form will only submit when this button is clicked
344
submitted = st.form_submit_button("Send Message", type="primary")
345
346
if submitted:
347
if name and email and message:
348
st.success("Message sent successfully!")
349
st.balloons()
350
else:
351
st.error("Please fill in all required fields (*)")
352
353
# Form with clear on submit
354
with st.form("survey_form", clear_on_submit=True):
355
st.write("Quick Survey")
356
357
rating = st.slider("How would you rate our service?", 1, 5, 3)
358
feedback = st.text_area("Additional feedback:")
359
recommend = st.checkbox("Would you recommend us to others?")
360
361
if st.form_submit_button("Submit Survey"):
362
st.success("Thank you for your feedback!")
363
st.write(f"Rating: {rating}/5")
364
st.write(f"Would recommend: {'Yes' if recommend else 'No'}")
365
```
366
367
### Containers and Placeholders
368
369
```python
370
# Generic container
371
with st.container():
372
st.write("This content is in a container")
373
st.info("Containers help organize related content")
374
375
# Container with border
376
with st.container(border=True):
377
st.write("This container has a visible border")
378
col1, col2 = st.columns(2)
379
with col1:
380
st.metric("Metric 1", "1,234", "12")
381
with col2:
382
st.metric("Metric 2", "5,678", "-5")
383
384
# Empty placeholder for dynamic content
385
placeholder = st.empty()
386
387
# Later, replace the placeholder content
388
import time
389
for i in range(5):
390
placeholder.text(f"Loading... {i+1}/5")
391
time.sleep(1)
392
393
placeholder.success("Loading complete!")
394
```
395
396
### Progress and Status
397
398
```python
399
# Progress bar
400
progress_bar = st.progress(0)
401
status_text = st.empty()
402
403
for i in range(100):
404
# Update progress
405
progress_bar.progress(i + 1)
406
status_text.text(f'Progress: {i+1}%')
407
time.sleep(0.01)
408
409
status_text.text('Processing complete!')
410
411
# Status container
412
with st.status("Processing data...", expanded=True) as status:
413
st.write("Loading dataset...")
414
time.sleep(1)
415
st.write("Cleaning data...")
416
time.sleep(1)
417
st.write("Running analysis...")
418
time.sleep(1)
419
status.update(label="Analysis complete!", state="complete", expanded=False)
420
421
# Spinner context manager
422
with st.spinner('Computing complex calculation...'):
423
time.sleep(2) # Simulate long computation
424
st.success('Calculation finished!')
425
```
426
427
### Popover Usage
428
429
```python
430
# Simple popover
431
with st.popover("Open popover"):
432
st.markdown("Hello World πŸ‘‹")
433
name = st.text_input("What's your name?")
434
if name:
435
st.write(f"Nice to meet you, {name}!")
436
437
# Popover with custom button
438
with st.popover("βš™οΈ Settings", help="Click to configure settings"):
439
st.checkbox("Enable notifications")
440
st.selectbox("Language", ["English", "Spanish", "French"])
441
theme = st.radio("Theme", ["Light", "Dark", "Auto"])
442
443
if st.button("Apply Settings"):
444
st.success("Settings applied!")
445
```
446
447
### Responsive Layout Patterns
448
449
```python
450
# Responsive metric dashboard
451
col1, col2, col3, col4 = st.columns(4)
452
453
metrics = [
454
("Revenue", "$125K", "12%"),
455
("Users", "2.8K", "-5%"),
456
("Conversion", "3.2%", "0.8%"),
457
("Retention", "87%", "2%")
458
]
459
460
for col, (label, value, delta) in zip([col1, col2, col3, col4], metrics):
461
with col:
462
st.metric(label, value, delta)
463
464
# Two-column layout with different content
465
left_col, right_col = st.columns([2, 1])
466
467
with left_col:
468
st.subheader("Main Content")
469
st.write("This is the main content area with more space.")
470
471
# Chart or main visualization
472
chart_data = pd.DataFrame(
473
np.random.randn(50, 3),
474
columns=['A', 'B', 'C']
475
)
476
st.line_chart(chart_data)
477
478
with right_col:
479
st.subheader("Sidebar Content")
480
st.write("Controls and filters go here.")
481
482
# Controls
483
show_data = st.checkbox("Show raw data")
484
chart_type = st.selectbox("Chart type", ["Line", "Area", "Bar"])
485
486
if show_data:
487
st.dataframe(chart_data.tail())
488
```