Reputation: 5951
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])
Upvotes: 2
Views: 2162
Reputation: 6629
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.
Upvotes: 0
Reputation: 5951
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])
Upvotes: 2