Search code examples
pythonflaskplotly-dashpy-shiny

Print output based on user input in dash (or shiny)


I would like to get inputs x and y from a user's input to a text box.

if x + 2*y 3*x*y > 100:
    print('Blurb 1')
else:
    print('Blurb 2')

This seems to be convoluted in dash with callbacks, etc, even though it could be self-contained and quite simple. Is there a simple way to do this within a web app? Other resources I found seem to assume a much more complex goal, so I am curious as to how much the code can be pared.


Solution

  • I don't think you can accomplish your task without defining a callback, but the code to get the work done is very short and simple. A possible solution could be the following:

    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    from dash.dependencies import Input, Output
    
    app = dash.Dash()
    
    app.layout = html.Div([
        html.H1("Simple input example"),
        dcc.Input(
            id='input-x',
            placeholder='Insert x value',
            type='number',
            value='',
        ),
        dcc.Input(
            id='input-y',
            placeholder='Insert y value',
            type='number',
            value='',
        ),
        html.Br(),
        html.Br(),
        html.Div(id='result')
        ])
    
    
    @app.callback(
        Output('result', 'children'),
        [Input('input-x', 'value'),
         Input('input-y', 'value')]
    )
    def update_result(x, y):
        return "The sum is: {}".format(x + y)
    
    
    if __name__ == '__main__':
            app.run_server(host='0.0.0.0', debug=True, port=50800)
    

    This is what you get: enter image description here

    The value of the sum is updated every time one of the two input boxes changes its values.