简体   繁体   中英

Update the plotly Dash dcc.Textarea value from what user inputs

I am creating a plotly Dash app with a text area from dash core components (dcc.Textarea). The end user wants to save the input from text area so that it can be reused next time the user goes in to update that field. I was able to save the save the text area content, but how do I update the default value for the field with the latest edit? I tried updating the 'value' and 'children' for the text area, but did not work. Here's the code.

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

I also tried:

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

The dcc.Textarea module takes arguments persistence and persistence_type. Set persistence=True and persistence_type='local'. Setting persistence to True will tell the application to save the last data entered and setting persistence_type to 'local' will save the last entered data to window.localStorage. So when the user quits the browser and comes back, the filed will have a default value of the data last entered. The code will be:

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))
                        ])

Everything about and below this code remains the same. Almost all the other dcc compoments will take in argument for persistence and persistence_type (eg. dcc.Dropdown).

For more info, you can go to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM