I have a function which plots a graph with a couple ipywidgets as inputs:
from IPython.display import clear_output def on_clicker(button): clear_output() @widgets.interact(dropdown=widgets.Dropdown(...), datepicker=widgets.DatePicker(...) def grapher(dropdown, datepicker): global recalculate ... some graphing stuff display(recalculate) recalculate.on_click(on_clicker)
The idea is that clicking recalculate calls the graph again and clears the past output. However, when I try this the widgets in the decorator remain under repeated use of recalculate:
Is there any way to clear these widgets as clear_output() does not seem to work?
You can use the clear_output() function to clear the output of the current cell in a Jupyter notebook. However, this will not clear the widgets that you have defined in your code. In order to clear the widgets, you will need to re-initialize them each time the on_clicker() function is called.
One way to do this would be to move the code that initializes the widgets inside the on_clicker() function, so that they are re-initialized each time the function is called.
Here is an example of how you could modify your code to achieve this:
from IPython.display import clear_output def on_clicker(button): clear_output() # Define the widgets inside the on_clicker function dropdown = widgets.Dropdown(...) datepicker = widgets.DatePicker(...) @widgets.interact(dropdown=dropdown, datepicker=datepicker) def grapher(dropdown, datepicker): global recalculate ... some graphing stuff display(recalculate) recalculate.on_click(on_clicker)
This way, when the on_clicker() function is called, it will clear the output and re-initialize the widgets, which should solve your problem.