10
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Python】Dashのcallbackにアニメーションをつける

Last updated at Posted at 2019-06-22

Dash Loading Component

ezgif.com-crop.gif

背景

Dashの可視化アプリケーションの描画に、loadingアニメーションをつけたいと思いました.

ちなみに、デフォルトだと以下のように何も変化がなく、inputを検知したことが伝わりにくくなってしまいます.

default_loading.gif

  • 環境

    • macOSX Mojave version 10.14,3
    • Python 3.6.1
    • 実行環境はlocal
  • 仕様

    • Dropdownのinputを受けてから2秒待機してcomponentを描画する
    • 2秒間の間にアニメーションを表示する

方法

Loading Componentで紹介されているdash_core_components.Loading()を使います.

アニメーションのあとで表示させたいcomponentをdcc.Loading()childrenとして与えます.

app.py
import dash
import dash_html_components as html
import dash_core_components as dcc
import time

from dash.dependencies import Input, Output

app = dash.Dash(__name__)
common_style = {'position': 'relative', 'width': '100%',
                'font-family': 'Dosis', 'text-align': 'center'}

app.layout = html.Div(
    children=[
        html.H1("Dash app with loading state", style={'margin-bottom': '10%'}),
        dcc.Dropdown(
            id='my-dropdown',
            options=[
                {'label': 'Cactus',
                 'value': 'https://image.flaticon.com/icons/svg/874/874979.svg'},
                {'label': 'Clownfish',
                 'value': 'https://image.flaticon.com/icons/svg/875/875011.svg'},
                {'label': 'Crab',
                    'value': 'https://image.flaticon.com/icons/svg/875/875010.svg'}
            ],
            value='https://image.flaticon.com/icons/svg/874/874979.svg'
        ),
        dcc.Loading(id="loading-1",
                    children=[
                        html.Div(id='output-container',
                                 )
                    ],
                    style={"margin": "10%"},
                    type="default"),
    ],
    style=common_style
)


@app.callback(
    Output('output-container', 'children'),
    [Input('my-dropdown', 'value')])
def input_triggers_spinner(value):
    time.sleep(2)
    return html.Img(src=value, height="30%", width="30%", style={"margin": "10%"})


if __name__ == "__main__":
    app.run_server(debug=False)

結果

ezgif.com-crop.gif

その他

spinnerの種類は上のdefaultを含めて5種類用意されているようです.

  • graph

graph.gif

  • cube

cube.gif

  • circle

circle.gif

  • dot

dot.gif

ぜひお試しください!

参考

10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?