【问题标题】:Plotly-Dash: Aggregate inputs and outputs to reflect complex python objectsPlotly-Dash:聚合输入和输出以反映复杂的 python 对象
【发布时间】:2019-06-19 17:46:03
【问题描述】:

如何使用多个 html 元素的聚合来表示一个对象。

例如,假设我有一个名为 TaggedCoordinates 的 Python 对象,其实例具有属性 t.x、t.y 和 t.tag。如果我想在页面中显示这样的实例,或者有一个表单要求用户输入一个,我会使用两个数字元素作为 x 和 y,并使用一个字符串元素作为标签。在回电中,我会有类似的东西

@callback(..., [...], [State(x_id), State(y_id), State(tag_id)])
def store_tagged_coordinate(x, y, tag):
    …

但我更喜欢这样的东西:

@callback(..., [...], [State(tag_coord_id)])
def store_tagged_coordinate(tag_coord):
    …

我怎样才能实现这样的目标? 我可以将 html 元素分组到具有特定 id 的 div 中(比如tag_coord_id),但是我如何让 dash 明白我想获得一个“结构”或它的组成部分的字典作为单个 python tag_coord 变量.

【问题讨论】:

    标签: python plotly-dash


    【解决方案1】:

    这是一个可能的解决方案(但会等待看看是否有更好的解决方案)。

    编写一个转换器函数,该函数将转换一个将与对象相关的 html 元素分组的 div,然后在回调函数中使用它。像这样:

    from dataclasses import dataclass
    
    @dataclass
    class TaggedCoord:
        x: float
        y: float
        tag: str
    
    def obj_for_div(d):
        return TaggedCoord(*[c.value for c in d.children])
    

    如果你的布局中有类似的东西:

    import dash_core_components as dcc
    import dash_html_components as html
    d = html.Div(children=[dcc.Input(id='x', value=0, type='number'), 
                           dcc.Input(id='y', value=0, type='number'), 
                           dcc.Input(id='tag', value='', type='text')],
          id='tagged_coord')
    
    @callback(..., [...], [State(tag_coord_id)])
    def store_tagged_coordinate(..., tag_coord):
        tag_coord = obj_for_div(tag_coord)
        ...
    

    看到了

    >>> obj_for_div(d)
    TaggedCoord(x=0, y=0, tag='')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2022-07-02
      • 2020-02-15
      • 2020-08-08
      • 2021-11-02
      • 1970-01-01
      • 2015-09-13
      相关资源
      最近更新 更多