【问题标题】:Plotly Dash- Using For Loop to Generate Multiple Headers Dynamically Inside a TabPlotly Dash - 使用 For 循环在选项卡内动态生成多个标题
【发布时间】:2021-12-13 19:43:28
【问题描述】:

我正在使用 Plotly/Dash 创建一个应用程序,并且我正在尝试根据下拉菜单中的用户输入动态更新显示在我的应用程序中的输入数量。所有这些都发生在一个选项卡内。但是,当我尝试通过回调执行 for 循环以获取固定 number(2) 标头时,我收到此错误消息:

组件的 children 属性是一个列表的列表,而不仅仅是一个列表。

在我定义的布局中:

[dcc.Input(type= 'number', id='input %i'%i) for i in range(2)]

而对应的装饰器是

[app.callback(Output('input %i' % i, 'value'),Input('dropdown-profile-specific', 'value'))(lambda value: None) for i in range(2)] 

我将如何取消嵌套以消除此错误。此外,如何使迭代次数取决于作为另一个回调的输出提供的列表的长度?

【问题讨论】:

    标签: python plotly plotly-dash plotly-python


    【解决方案1】:

    您要使用的是pattern matching callbacks 样式实现。这是第一个示例的稍微修改的版本,我相信这就是您正在寻找的。​​p>

    在布局中,您需要输入数量的下拉菜单和 div 持有人 保存动态创建的输入:

    dcc.Dropdown(id='num-inputs', options=[{'label': i, 'value': i} for i in range(1,6)]), # or whatever options you want
    html.Div(id='input-container', children=[]),
    html.Div(id='inputs-vals') # this is just to show the input values
    

    回调会将提供输入数量的下拉菜单作为输入,输出将是持有人 div 的子项,如果您想更新现有的子项,您可以将其添加为 State 输入参数(@ 987654323@)。

    @app.callback(
        Output('input-container', 'children'),
        Input('num-inputs', 'value')
    )
    def add_inputs(num_inputs):
        # Alternatively update existing children
        if num_inputs is None: return ""
        return [dcc.Input(type='number', id={'type':'inputs', 'index':i}) 
               for i in range(num_inputs)
        ]
    

    最后一部分是模式匹配回调发挥作用的地方。我们可以使用我们添加到输入的 id dict 的类型值来为每个输入做一些事情。

    @app.callback(
        Output('input-vals', 'children'),
        Input({'type': 'inputs', 'index': ALL}, 'value')
    )
    def use_inputs(values):
        return html.Div([
            html.Div(f'Input {i+1} = {v}') 
            for (i,v) in enumerate(values)
        ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-23
      • 2021-10-06
      • 2011-05-02
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多