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.50.0

components-config.md docs/

1
# Components and Configuration
2
3
Custom component framework and column configuration for data editors and dataframes. These features enable extending Streamlit with custom functionality and fine-grained control over data presentation.
4
5
## Capabilities
6
7
### Custom Components
8
9
Framework for creating and integrating custom HTML/JavaScript components into Streamlit applications.
10
11
```python { .api }
12
# Available in st.components.v1 namespace
13
def html(html, *, width=None, height=None, scrolling=False):
14
"""
15
Display HTML content in an iframe with optional sizing and scrolling.
16
17
Args:
18
html (str): HTML content to display
19
width (int, optional): Component width in pixels
20
height (int, optional): Component height in pixels
21
scrolling (bool): Whether to allow scrolling within the iframe
22
23
Returns:
24
Any: Data returned from the HTML component (if any)
25
"""
26
27
def iframe(src, *, width=None, height=None, scrolling=False):
28
"""
29
Display external web page or content in an iframe.
30
31
Args:
32
src (str): URL of the content to display
33
width (int, optional): Iframe width in pixels
34
height (int, optional): Iframe height in pixels
35
scrolling (bool): Whether to allow scrolling within the iframe
36
37
Returns:
38
Any: Data returned from the iframe (if any)
39
"""
40
41
def declare_component(name, path=None, url=None):
42
"""
43
Declare a custom Streamlit component for use in the application.
44
45
Args:
46
name (str): Component name for identification
47
path (str, optional): Local path to component files
48
url (str, optional): URL where component is hosted
49
50
Returns:
51
callable: Component function that can be called to render the component
52
"""
53
```
54
55
Example usage:
56
```python
57
import streamlit.components.v1 as components
58
59
# Simple HTML component
60
html_content = """
61
<div style="background: linear-gradient(90deg, #ff6b6b, #4ecdc4);
62
color: white; padding: 20px; border-radius: 10px; text-align: center;">
63
<h2>Custom HTML Component</h2>
64
<p>This is rendered from HTML!</p>
65
<button onclick="window.parent.postMessage({type: 'click', data: 'Button clicked!'})">
66
Click Me
67
</button>
68
</div>
69
"""
70
71
# Display HTML with return value
72
result = components.html(html_content, height=150)
73
if result:
74
st.write(f"Component returned: {result}")
75
76
# Iframe component
77
components.iframe("https://example.com", height=400)
78
79
# Custom component declaration
80
# Component files in ./my_component/
81
my_component = components.declare_component("my_component", path="./my_component")
82
83
# Use custom component
84
component_value = my_component(
85
name="example",
86
value=42,
87
options=["A", "B", "C"]
88
)
89
```
90
91
### Column Configuration
92
93
Comprehensive configuration system for customizing dataframe and data editor column behavior and appearance.
94
95
```python { .api }
96
# Available in st.column_config namespace
97
98
class Column:
99
"""
100
Base column configuration with common properties.
101
102
Args:
103
label (str, optional): Column display name
104
width (str or int, optional): Column width ("small", "medium", "large", or pixels)
105
help (str, optional): Tooltip text for column header
106
disabled (bool, optional): Whether column is read-only
107
required (bool, optional): Whether column value is required
108
"""
109
110
class TextColumn(Column):
111
"""
112
Text column configuration for string data.
113
114
Args:
115
label (str, optional): Column display name
116
width (str or int, optional): Column width
117
help (str, optional): Tooltip text
118
disabled (bool, optional): Whether column is read-only
119
required (bool, optional): Whether column value is required
120
default (str, optional): Default value for new rows
121
max_chars (int, optional): Maximum number of characters allowed
122
validate (callable, optional): Validation function for input
123
"""
124
125
class NumberColumn(Column):
126
"""
127
Number column configuration for numeric data.
128
129
Args:
130
label (str, optional): Column display name
131
width (str or int, optional): Column width
132
help (str, optional): Tooltip text
133
disabled (bool, optional): Whether column is read-only
134
required (bool, optional): Whether column value is required
135
default (float, optional): Default value for new rows
136
min_value (float, optional): Minimum allowed value
137
max_value (float, optional): Maximum allowed value
138
step (float, optional): Step size for increment/decrement
139
format (str, optional): Number format string (e.g., "%.2f", "%d")
140
"""
141
142
class CheckboxColumn(Column):
143
"""
144
Checkbox column configuration for boolean data.
145
146
Args:
147
label (str, optional): Column display name
148
width (str or int, optional): Column width
149
help (str, optional): Tooltip text
150
disabled (bool, optional): Whether column is read-only
151
required (bool, optional): Whether column value is required
152
default (bool, optional): Default value for new rows
153
"""
154
155
class SelectboxColumn(Column):
156
"""
157
Selectbox column configuration for categorical data.
158
159
Args:
160
label (str, optional): Column display name
161
width (str or int, optional): Column width
162
help (str, optional): Tooltip text
163
disabled (bool, optional): Whether column is read-only
164
required (bool, optional): Whether column value is required
165
default (Any, optional): Default selected value
166
options (list): Available options to choose from
167
"""
168
169
class DatetimeColumn(Column):
170
"""
171
Datetime column configuration for timestamp data.
172
173
Args:
174
label (str, optional): Column display name
175
width (str or int, optional): Column width
176
help (str, optional): Tooltip text
177
disabled (bool, optional): Whether column is read-only
178
required (bool, optional): Whether column value is required
179
default (datetime, optional): Default datetime value
180
min_value (datetime, optional): Minimum allowed datetime
181
max_value (datetime, optional): Maximum allowed datetime
182
format (str, optional): Datetime display format
183
step (int, optional): Step size in seconds
184
"""
185
186
class DateColumn(Column):
187
"""
188
Date column configuration for date-only data.
189
190
Args:
191
label (str, optional): Column display name
192
width (str or int, optional): Column width
193
help (str, optional): Tooltip text
194
disabled (bool, optional): Whether column is read-only
195
required (bool, optional): Whether column value is required
196
default (date, optional): Default date value
197
min_value (date, optional): Minimum allowed date
198
max_value (date, optional): Maximum allowed date
199
format (str, optional): Date display format
200
"""
201
202
class TimeColumn(Column):
203
"""
204
Time column configuration for time-only data.
205
206
Args:
207
label (str, optional): Column display name
208
width (str or int, optional): Column width
209
help (str, optional): Tooltip text
210
disabled (bool, optional): Whether column is read-only
211
required (bool, optional): Whether column value is required
212
default (time, optional): Default time value
213
min_value (time, optional): Minimum allowed time
214
max_value (time, optional): Maximum allowed time
215
format (str, optional): Time display format
216
step (int, optional): Step size in seconds
217
"""
218
219
class ListColumn(Column):
220
"""
221
List column configuration for array/list data.
222
223
Args:
224
label (str, optional): Column display name
225
width (str or int, optional): Column width
226
help (str, optional): Tooltip text
227
"""
228
229
class LinkColumn(Column):
230
"""
231
Link column configuration for URL data with clickable links.
232
233
Args:
234
label (str, optional): Column display name
235
width (str or int, optional): Column width
236
help (str, optional): Tooltip text
237
disabled (bool, optional): Whether column is read-only
238
required (bool, optional): Whether column value is required
239
default (str, optional): Default URL value
240
max_chars (int, optional): Maximum URL length
241
validate (callable, optional): URL validation function
242
display_text (str or callable, optional): Text to display instead of URL
243
"""
244
245
class ImageColumn(Column):
246
"""
247
Image column configuration for displaying images from URLs.
248
249
Args:
250
label (str, optional): Column display name
251
width (str or int, optional): Column width
252
help (str, optional): Tooltip text
253
"""
254
255
class LineChartColumn(Column):
256
"""
257
Line chart column configuration for displaying small charts in cells.
258
259
Args:
260
label (str, optional): Column display name
261
width (str or int, optional): Column width
262
help (str, optional): Tooltip text
263
y_min (float, optional): Minimum Y-axis value
264
y_max (float, optional): Maximum Y-axis value
265
"""
266
267
class BarChartColumn(Column):
268
"""
269
Bar chart column configuration for displaying small bar charts in cells.
270
271
Args:
272
label (str, optional): Column display name
273
width (str or int, optional): Column width
274
help (str, optional): Tooltip text
275
y_min (float, optional): Minimum Y-axis value
276
y_max (float, optional): Maximum Y-axis value
277
"""
278
279
class ProgressColumn(Column):
280
"""
281
Progress bar column configuration for displaying progress indicators.
282
283
Args:
284
label (str, optional): Column display name
285
width (str or int, optional): Column width
286
help (str, optional): Tooltip text
287
min_value (float, optional): Minimum progress value (default 0)
288
max_value (float, optional): Maximum progress value (default 100)
289
format (str, optional): Progress display format
290
"""
291
```
292
293
Example usage:
294
```python
295
import pandas as pd
296
import streamlit as st
297
298
# Sample dataframe
299
data = pd.DataFrame({
300
"name": ["Alice", "Bob", "Charlie"],
301
"age": [25, 30, 35],
302
"active": [True, False, True],
303
"category": ["A", "B", "A"],
304
"score": [85.5, 92.1, 78.3],
305
"signup_date": ["2023-01-15", "2023-02-20", "2023-03-10"],
306
"website": ["https://alice.com", "https://bob.org", "https://charlie.net"],
307
"progress": [75, 90, 60],
308
"trend": [[1,3,2,4], [2,1,4,3], [3,4,2,1]]
309
})
310
311
# Configure columns
312
column_config = {
313
"name": st.column_config.TextColumn(
314
"Full Name",
315
help="Employee full name",
316
max_chars=50,
317
required=True
318
),
319
"age": st.column_config.NumberColumn(
320
"Age",
321
help="Employee age in years",
322
min_value=18,
323
max_value=65,
324
step=1,
325
format="%d years"
326
),
327
"active": st.column_config.CheckboxColumn(
328
"Active Status",
329
help="Whether employee is currently active",
330
default=True
331
),
332
"category": st.column_config.SelectboxColumn(
333
"Department",
334
help="Employee department",
335
options=["A", "B", "C"],
336
required=True
337
),
338
"score": st.column_config.NumberColumn(
339
"Performance Score",
340
help="Performance rating out of 100",
341
min_value=0,
342
max_value=100,
343
format="%.1f"
344
),
345
"signup_date": st.column_config.DateColumn(
346
"Start Date",
347
help="Employee start date",
348
format="YYYY-MM-DD"
349
),
350
"website": st.column_config.LinkColumn(
351
"Personal Website",
352
help="Employee personal website",
353
display_text="Visit"
354
),
355
"progress": st.column_config.ProgressColumn(
356
"Project Progress",
357
help="Current project completion percentage",
358
min_value=0,
359
max_value=100,
360
format="%d%%"
361
),
362
"trend": st.column_config.LineChartColumn(
363
"Performance Trend",
364
help="Performance over last 4 quarters"
365
)
366
}
367
368
# Display configured dataframe
369
st.data_editor(
370
data,
371
column_config=column_config,
372
use_container_width=True,
373
num_rows="dynamic" # Allow adding/removing rows
374
)
375
```
376
377
### Advanced Configuration Patterns
378
379
#### Conditional Column Configuration
380
381
```python
382
def get_column_config(user_role, data_types):
383
"""Generate column config based on user role and data."""
384
config = {}
385
386
for col_name, col_type in data_types.items():
387
base_config = {"help": f"{col_name} column"}
388
389
# Role-based permissions
390
if user_role != "admin":
391
base_config["disabled"] = col_name in ["salary", "ssn"]
392
393
# Type-specific configuration
394
if col_type == "currency":
395
config[col_name] = st.column_config.NumberColumn(
396
col_name.title(),
397
format="$%.2f",
398
min_value=0,
399
**base_config
400
)
401
elif col_type == "percentage":
402
config[col_name] = st.column_config.ProgressColumn(
403
col_name.title(),
404
min_value=0,
405
max_value=100,
406
format="%d%%",
407
**base_config
408
)
409
elif col_type == "category":
410
config[col_name] = st.column_config.SelectboxColumn(
411
col_name.title(),
412
options=get_category_options(col_name),
413
**base_config
414
)
415
416
return config
417
418
# Usage
419
user_role = get_current_user_role()
420
data_types = analyze_dataframe_types(df)
421
column_config = get_column_config(user_role, data_types)
422
423
st.data_editor(df, column_config=column_config)
424
```
425
426
#### Dynamic Image Display
427
428
```python
429
# Image column with dynamic URLs
430
image_data = pd.DataFrame({
431
"product_name": ["Widget A", "Widget B", "Widget C"],
432
"image_url": [
433
"https://example.com/images/widget-a.jpg",
434
"https://example.com/images/widget-b.jpg",
435
"https://example.com/images/widget-c.jpg"
436
],
437
"price": [19.99, 24.99, 29.99]
438
})
439
440
column_config = {
441
"product_name": st.column_config.TextColumn("Product", width="medium"),
442
"image_url": st.column_config.ImageColumn("Product Image", width="large"),
443
"price": st.column_config.NumberColumn("Price", format="$%.2f")
444
}
445
446
st.dataframe(image_data, column_config=column_config)
447
```
448
449
#### Interactive Chart Columns
450
451
```python
452
# Line chart column with time series data
453
chart_data = pd.DataFrame({
454
"stock": ["AAPL", "GOOGL", "MSFT"],
455
"current_price": [150.25, 2800.50, 300.75],
456
"price_history": [
457
[145, 148, 152, 150], # AAPL last 4 days
458
[2750, 2780, 2820, 2800], # GOOGL
459
[295, 298, 305, 301] # MSFT
460
],
461
"volatility": [0.15, 0.12, 0.18]
462
})
463
464
column_config = {
465
"stock": st.column_config.TextColumn("Symbol", width="small"),
466
"current_price": st.column_config.NumberColumn(
467
"Price",
468
format="$%.2f"
469
),
470
"price_history": st.column_config.LineChartColumn(
471
"4-Day Trend",
472
width="medium"
473
),
474
"volatility": st.column_config.ProgressColumn(
475
"Volatility",
476
min_value=0,
477
max_value=1,
478
format="%.1%%"
479
)
480
}
481
482
st.dataframe(chart_data, column_config=column_config)
483
```
484
485
### Custom Component Development
486
487
#### Basic HTML Component
488
489
```python
490
# my_component.py
491
import streamlit.components.v1 as components
492
493
def color_picker_component(default_color="#000000", key=None):
494
"""Custom color picker component."""
495
html_template = f"""
496
<div>
497
<label for="color-picker">Choose a color:</label>
498
<input type="color" id="color-picker" value="{default_color}"
499
onchange="sendColor(this.value)">
500
<div id="preview" style="width:50px;height:50px;background:{default_color};margin-top:10px;"></div>
501
</div>
502
503
<script>
504
function sendColor(color) {{
505
document.getElementById('preview').style.background = color;
506
window.parent.postMessage({{
507
type: 'streamlit:setComponentValue',
508
value: color
509
}});
510
}}
511
</script>
512
"""
513
514
return components.html(html_template, height=100, key=key)
515
516
# Usage
517
selected_color = color_picker_component(default_color="#ff6b6b", key="color")
518
if selected_color:
519
st.write(f"Selected color: {selected_color}")
520
```
521
522
#### React-based Component
523
524
```python
525
# Declare React component (assumes component built separately)
526
react_component = components.declare_component(
527
"my_react_component",
528
url="http://localhost:3001" # Development server
529
)
530
531
def data_table_component(data, editable=True, key=None):
532
"""Custom data table with advanced features."""
533
return react_component(
534
data=data.to_dict('records'),
535
columns=list(data.columns),
536
editable=editable,
537
key=key
538
)
539
540
# Usage
541
df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
542
edited_data = data_table_component(df, editable=True, key="table")
543
544
if edited_data:
545
st.write("Edited data:", edited_data)
546
```
547
548
#### Component with Bidirectional Communication
549
550
```python
551
def interactive_chart_component(data, chart_type="bar", key=None):
552
"""Interactive chart that returns clicked data point."""
553
554
# Convert data to JSON for JavaScript
555
chart_data = data.to_dict('records')
556
557
html_template = f"""
558
<div id="chart-container" style="width: 100%; height: 400px;"></div>
559
560
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
561
<script>
562
const data = {chart_data};
563
const chartType = "{chart_type}";
564
565
// Create Plotly chart
566
const plotData = [{{
567
x: data.map(d => d.x),
568
y: data.map(d => d.y),
569
type: chartType,
570
marker: {{ color: 'rgb(55, 128, 191)' }}
571
}}];
572
573
const layout = {{
574
title: 'Interactive Chart',
575
xaxis: {{ title: 'X Axis' }},
576
yaxis: {{ title: 'Y Axis' }}
577
}};
578
579
Plotly.newPlot('chart-container', plotData, layout);
580
581
// Handle click events
582
document.getElementById('chart-container').on('plotly_click', function(eventData) {{
583
const point = eventData.points[0];
584
const clickedData = {{
585
x: point.x,
586
y: point.y,
587
pointIndex: point.pointIndex
588
}};
589
590
// Send data back to Streamlit
591
window.parent.postMessage({{
592
type: 'streamlit:setComponentValue',
593
value: clickedData
594
}});
595
}});
596
</script>
597
"""
598
599
return components.html(html_template, height=450, key=key)
600
601
# Usage
602
chart_data = pd.DataFrame({
603
'x': ['A', 'B', 'C', 'D'],
604
'y': [10, 15, 13, 17]
605
})
606
607
clicked_point = interactive_chart_component(chart_data, chart_type="bar", key="chart")
608
609
if clicked_point:
610
st.write(f"Clicked point: {clicked_point}")
611
st.json(clicked_point)
612
```