Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Clearing decorator ipywidgets

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:

Stacked widgets

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there any way to clear these widgets as clear_output() does not seem to work?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading