首页 > 解决方案 > 如何使用回调在 Python 中使用 Dash 添加到存储在 Div 中的字符串?

问题描述

我在 Python 中使用破折号来创建仪表板。每次生成新字符串作为另一个仪表板元素/进程的一部分时,我想更新存储在 Div 中的字符串。到目前为止,我为此创建回调的最佳尝试是不成功的,但旨在通过以下方式工作:

  1. new_string作为输入。
  2. 将其添加到output_div.
  3. 将's 添加到由 it's 给定的new_string已收集的字符串数据中。output_divstate

这是回调代码:

@Dashboard.callback(
                    Output('output_div', 'children'),
                    [Input('new_string', 'children')],
                    [State('output_div', 'children')]
                   )
def create_complete_string(new_string, string_in_output_div_so_far):
    if string_in_output_div_so_far is None:
       return new_string
    else:
       return string_in_output_div_so_far + new_string

这并不像希望的那样工作,因为它只输出一个实例new_string(生成的许多实例中的最后一个),output_div而是将它们全部连接在一起。

谁能建议我做错了什么?

谢谢 :)

标签: pythonplotly-dash

解决方案


使用给定的代码片段很难找出错误,如果您可以将最小的复制器粘贴为片段会很好;但这里有一个最小的工作代码,可以满足;

import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash(__name__)

app.layout = html.Div([
            dcc.Input(id="text"),
            html.Div(id='new_string'),
            html.Div(id='output_div'),
    ])


@app.callback(
            Output('new_string', 'children'),
            [Input('text', 'value')]
        )
def output_text(text):
    return text

推荐阅读