问题
I am using ipython widgets in my jupyter notebook. Now when kernel is restarted, the widget state is lost and a message is displayed:
“Jupyter widget could not be displayed because the widget state could not be found. This could happen if the kernel storing the widget is no longer available, or if the widget state was not saved in the notebook. You may be able to create the widget by running the appropriate cells”
So when a user reopens his notebook after a kernel restart, he doesn't find the widget in the notebook that he had earlier. We want to save all widgets state so the after kernel restart when user reopens the notebook, he finds all his widgets intact.
PS: There is "save widget state" menu option which does that but that is a manual step and we want widgets state to be saved through our python code.
回答1:
This is a bit of a hack and may have unintended consequences. On every function you call from interactive, you can add a call to the function below:
def save_with_widgets ():
display(
HTML('<script>Jupyter.menubar.actions._actions["widgets:save-with-widgets"].handler()</script>') )
It will save your notebook (be aware of that), and the widget state with it.
However, please note that, when you run the cell that has the actual widget, it will not respect the saved state.
That's not specific to the function above; the same happens if you use the save widget state menu option.
So... I'm not really sure how useful that option is. It will save the state to show you how the notebook looked like last time, but you won't be able to actually reuse the ticket state on the next run (well, you can write the values down and re-enter them, but I don't think that is what you wanted...)
来源:https://stackoverflow.com/questions/59123005/how-to-save-state-of-ipython-widgets-in-jupyter-notebook-using-python-code