Save and restore widget values... the right way?

Context: a financial planning notebook with many input widgets

For a few years I’ve been using a simple method to save and restore widget values to assist a user with leaving and returning to the notebook. Typically, one uses the notebook for a few weeks and then returns the following year. I found that text based widgets (BoundedFloatText BoundedIntText Text) and Dropdown widgets worked well for this, but Checkbox didn’t update state upon setting the value from the code.

Specifically, I used a Button in my notebook, whose onClick handler did this:

ps = pandas.Series(index=[r[0] for r in params],
                   data=[r[1].value for r in params])
ps.to_csv(path_or_buf=pfname.value)

where params is a 2D array of name, widget, default-value.

#       name,  widget, default
params = [ 
   ['byear', byear_box,  2024 ],

etc.

A second button’s onClick handler did this:

ps = pandas.read_csv(filepath_or_buffer=pfname.value,
                 index_col=0, keep_default_na=False)
for name, wdgt, dflt in params:
    wdgt.value = ps.loc[key]['0']

I’ve omitted some detail about using the default values when the name is not present in the file.

As I say, this worked fine for years, but recently the Dropdown widgets stopped updating. The same wdgt.value = X worked fine when manually executed from another notebook cell, but not when called in the button’s onClick

I’ve got a workaround… since the text widgets still work, I use a surrogate text widget to receive the Dropdown values, and link the surrogate text widget and the Dropdownusing

widgets.link((surrogate, 'value'), (wgt, 'value'))

So, I have it working, but it seems there ought to be a better way.

I suspect my problem is either a timing issue (because I did add widgets between working and not working versions, which might have pushed the update time beyond some threshold), or a state/thread issue, or both.

If you have a suggestion for a better way to do this, I’l love to hear about it!

The code for my implementation is below. If you follow the link and click the Code tab, Github will highlight the lines in the repo.

1 Like

Addendum: I neglected to mention that the Exception I get when attempting to set the value of the Dropdown from the Button’s onClick callback is Invalid selection: value not found, which is nonsense, of course, since I can set same value manually.