【问题标题】:Use list as variable in a for loop to switch data with callback in Plotly Dash在 for 循环中使用列表作为变量在 Plotly Dash 中使用回调切换数据
【发布时间】:2021-10-27 04:02:19
【问题描述】:

我有一个由两个键和列表组成的字典。我想在 Plotly Dash 中使用回调将列表切换为显示变量。该列表在childrenhtml.Div 内的for 循环中使用。请在下面找到示例:

import dash
from dash import dcc
from dash import html
from pathlib import Path
from dash.dependencies import Input, Output

app = dash.Dash(__name__)

my_data = {'fruit_list1': ['apple', 'orange', 'peach'], 'fruit_list2': ['cherry', 'grape', 'strawberry']}
my_list = ['fruit_list1', 'fruit_list2']

def fruit_list(fruitlist):
        return(my_data[fruitlist])

def add_value(fruit):
        return html.P('Type of fruit : ' + fruit)

app.layout = html.Div(children=[
        html.P('Select fruit list : '),
        dcc.Dropdown(
                id='change-the-list',
                value='fruit_list1',
                clearable=False,
                options=[
                        {'label': value_input, 'value': value_input} for value_input in my_list]
                ),
        html.Div(
                id='fruit-list',
                children=[add_value(fruit) for fruit in fruit_list('fruit_list1')]
                )
        ])

@app.callback(Output('fruit-list', 'children'),
        Input('change-the-list', 'value'))

def update_list(list_input):
        return {
        # What do I do here to switch from 'fruit_list1' to 'fruit_list2'?
        }

if __name__ == '__main__':
        app.run_server(debug=False, host='0.0.0.0', port=8051)

在这种情况下,如何从'fruit_list1' 动态切换到'fruit_list2' 以反映使用dcc.Dropdown 的更改?提前致谢。

【问题讨论】:

    标签: python-3.x callback plotly-dash


    【解决方案1】:

    找到答案。我只需要返回整个children

    @app.callback(Output('fruit-list', 'children'),
            Input('change-the-list', 'value'))
    
    def update_list(list_input):
            children=[add_value(fruit) for fruit in fruit_list(list_input)]
            return children
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-27
      • 2018-11-14
      • 2021-08-08
      • 2020-07-01
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多