2

I would like to clear the previous output when the widget is rerun.

for example

from IPython.display import display, clear_output

import ipywidgets as widgets
from datetime import datetime, timedelta
button = widgets.Button(description='RUN',button_style='info')

def on_button_clicked(b):

    # DO SOMETHING #

    out = widgets.Output()
    out.clear_output(wait=True)
    out.append_stdout(f'Ran at {datetime.now()}')
    display(out)

button.on_click(on_button_clicked)
widgets.VBox([button])

Every time i click on the RUN button it "appends" the print statement

I also tried this:

button = widgets.Button(description='RUN',button_style='info')

def on_button_clicked(b):

    # DO SOMETHING #

    out = widgets.Output()
    out.clear_output(wait=True)
    with out:
        print(f'Ran at {datetime.now()}')
    display(out)

button.on_click(on_button_clicked)
widgets.VBox([button])
1
  • NameError: name 'button' is not defined Commented May 29, 2020 at 8:12

2 Answers 2

2

This works


from IPython.display import display, clear_output

import ipywidgets as widgets
from datetime import datetime, timedelta


button = widgets.Button(description='RUN',button_style='info')

out = widgets.Output() 

@out.capture(clear_output=True)
def on_button_clicked(b):
    # DO SOMETHING #
    print ( f'Ran at {datetime.now()}')


button.on_click(on_button_clicked)
widgets.VBox([button])

Sign up to request clarification or add additional context in comments.

Comments

0

Looks like you're running ipython 3.8... that's 5 years old. I strongly recommend upgrading to a later version, but totally understand that this is not always possible depending on time and resources.

Here's the documentation for the ipython 3.x display widget:
https://ipython.org/ipython-doc/3/api/generated/IPython.display.html#functions

Try this:

from IPython.display import clear_output
import ipywidgets as widgets
from datetime import datetime

button = widgets.Button(description='RUN',button_style='info')

def on_button_clicked(b):
    # DO SOMETHING #
    print(f'Ran at {datetime.now()}')

    # This will clear the cell output the NEXT time the button is pressed
    clear_output(wait=True)

button.on_click(on_button_clicked)
widgets.VBox([button])

There have been some reports of "shaking" in the notebook when print() is used. If you notice this, try using print('message', flush=True) instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.