根据用户输入更新Dash dcc.Textarea值

时间:2020-05-27 14:29:29

标签: python plotly-dash

我正在创建一个仪表板Dash应用程序,其中包含来自仪表板核心组件(dcc.Textarea)的文本区域。最终用户希望保存来自文本区域的输入,以便下次用户进入该字段时可以重新使用该输入。我能够保存文本区域的内容,但是如何使用最新的编辑来更新该字段的默认值?我尝试更新文本区域的“值”和“子项”,但是没有用。这是代码。

folder=r'C:\Temp'
def text_ar_val(file='TextBox1.txt'):
    with open(folder+fr'\Data\{file}','r') as f:
        return f.read()
app = dash.Dash(__name__)
app.layout = html.Div([dcc.Textarea(
                                id='textarea1', className='textarea1',
                                value=text_ar_val()
                            ),
                            html.Div(daq.StopButton(id='save1',className="button",
                                                    buttonText='Save', n_clicks=0))
                        ])
@app.callback(Output('textarea1', 'children'),
              [Input('save1', 'n_clicks'), Input('textarea1','value')])
def textbox1(n_clicks, value):
    if n_clicks>0:
        global folder
        with open(folder+r'\Data\TextBox1.txt','w') as file:
            file.write(value)
            return value

我也尝试过:

@app.callback(Output('textarea1', 'value'),
          [Input('save1', 'n_clicks'), Input('textarea1','value')])

1 个答案:

答案 0 :(得分:1)

dcc.Textarea模块采用参数persistence和persistence_type。设置persistence = True和persistence_type ='local'。将persistence_type设置为True将告诉应用程序保存最后输入的数据,将persistence_type设置为“ local”会将最后输入的数据保存到window.localStorage。因此,当用户退出浏览器并返回时,字段将具有最后输入的数据的默认值。该代码将是:

app.layout = html.Div([dcc.Textarea(
                                id='textarea1', className='textarea1',
                                value=text_ar_val(),
                                persistence=True, persistence_type='local'
                            ),
                            html.Div(daq.StopButton(id='save1',className="button",
                                                    buttonText='Save', n_clicks=0))
                        ])

此代码及其以下的所有内容均保持不变。几乎所有其他dcc组件都会接受persistence和persistence_type的参数(例如dcc.Dropdown)。

有关更多信息,您可以转到:

https://dash.plotly.com/dash-core-components/textarea