peter
peter

Reputation: 786

Python Plotly Dash: Automatically iterate through slider, 'PLAY BUTTON'

I would like to include a component in my Dash App, that automatically goes through all of the values of a slider. Basically a ‘play button’. As the consequence the callback with the slider value as input should fire and update the output element.

Does anyone know how to do it?

Here is some sample code from the official docs:

from dash import Dash, dcc, html, Input, Output

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    dcc.Slider(0, 20, 5,
               value=10,
               id='my-slider'
    ),
    html.Div(id='slider-output-container')
])

@app.callback(
    Output('slider-output-container', 'children'),
    Input('my-slider', 'value'))
def update_output(value):
    return 'You have selected "{}"'.format(value)

if __name__ == '__main__':
    app.run_server(debug=True)

Upvotes: 0

Views: 1315

Answers (1)

r-beginners
r-beginners

Reputation: 35135

I am inexperienced in Dash, so I looked into it and found a case study answer on the plotly communication site. I have modified it to meet your requirements. As far as I understand it, you need two callbacks, one to start and stop the button click and one to return the value obtained from the animation and the new slider value. Note that it does not have a function to automatically stop when the maximum value is reached.

from dash import Dash, dcc, html, Input, Output, State
from jupyter_dash import JupyterDash # Add for my environment

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

#app = Dash(__name__, external_stylesheets=external_stylesheets)
app = JupyterDash(__name__, external_stylesheets=external_stylesheets) # Add for my environment

step_num = 5
app.layout = html.Div([
    dcc.Interval(id="animate", disabled=True),
    dcc.Slider(min=0,
               max=50, 
               step=5,
               value=0,
               id='my-slider'
    ),
    html.Button("Play/Stop", id="play"),
    html.Div(id='slider-output-container')
])

@app.callback(
    Output('slider-output-container', 'children'),
    Output("my-slider", "value"),
    Input('animate', 'n_intervals'),
    State('my-slider', 'value'),
    prevent_initial_call=True,
)
def update_output(n, selected_value):
    selected_value = (n%11)*step_num
    return 'You have selected "{}"'.format(selected_value), selected_value

@app.callback(
    Output("animate", "disabled"),
    Input("play", "n_clicks"),
    State("animate", "disabled"),
)
def toggle(n, playing):
    if n:
        return not playing
    return playing

if __name__ == '__main__':
    app.run_server(debug=True, port=8051, mode='inline') #Add for my environment

enter image description here

Upvotes: 2

Related Questions