Last active
March 5, 2018 11:58
-
-
Save jwhendy/5c59da4fee9c1c65c1c5a5fb7487a71e to your computer and use it in GitHub Desktop.
A plotly dash app where I want to have a dynamic number of text boxes and access their values from a callback when a button is pushed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import dash | |
from dash.dependencies import Input, Output, Event, State | |
import dash_core_components as dcc | |
import dash_html_components as html | |
app = dash.Dash() | |
app.config.supress_callback_exceptions = True | |
app.css.append_css({'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'}) | |
## function to generate input widgets | |
## num_slider is a slider from 1-4, initialized to 1 | |
## text_boxes is a div placeholder for on-the-fly generated text fields | |
## run_button is a button | |
def generate_inputs(): | |
num_slider = [html.Label(html.Strong('select number')), | |
dcc.Slider(id='num', min=1, max=4, value=1, | |
marks={i: i for i in range(5)})] | |
text_boxes = [html.Label(html.Strong('text inputs')), | |
html.Div(id='boxes')] | |
run_button = [html.Label(html.Strong('ready?')), | |
html.Button('run!', id='run', n_clicks=0)] | |
input_list = [num_slider, text_boxes, run_button] | |
widgets = list() | |
for sublist in input_list: | |
sublist.append(html.H1('')) | |
for item in sublist: | |
widgets.append(item) | |
return widgets | |
## generate_input and an empty ghost div where I can send results | |
app.layout = html.Div([ | |
html.H2('app'), | |
html.Div(generate_inputs(), | |
style={'float': 'left', 'width': '20%', 'padding': '0 0 50px 0'}), | |
html.Div(id='lookups', | |
style={'float': 'right', 'width': '75%'}) | |
]) | |
## when the number of the slider changes, run this | |
## for this demo, not doing this as I've hardcoded id='a'. In practice | |
## I'd have the id be str(i) or something. | |
@app.callback( | |
Output('boxes', 'children'), | |
[Input('num', 'value')]) | |
def ins_generate(n): | |
return [html.Div( | |
dcc.Input(id='a', | |
placeholder='a thing', value='thing', | |
size=40, type='text')) for i in range(n)] | |
## when the button is clicked, access our on-the-fly field | |
@app.callback( | |
Output('lookups', 'children'), | |
[Input('run', 'n_clicks')], | |
[State('a', 'value')]) | |
def create_lookup(n_clicks, val): | |
print(val) | |
if __name__ == '__main__': | |
app.run_server(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, interesting post. Did not work for me though. Got "error loading dependencies".