每次运行时清除小部件的先前输出

时间:2020-05-29 08:06:44

标签: python jupyter ipywidgets

当小部件重新运行时,我想清除先前的输出。

例如

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])

每次我点击RUN按钮时,它都会“附加”打印声明

我也尝试过:

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])

2 个答案:

答案 0 :(得分:1)

这有效


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])

答案 1 :(得分:0)

好像您正在运行ipython 3.8 ...已有5年历史了。我强烈建议升级到更高版本,但完全理解这并非总是可能的,具体取决于时间和资源。

以下是ipython 3.x显示小部件的文档:
https://ipython.org/ipython-doc/3/api/generated/IPython.display.html#functions

尝试一下:

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])

使用print()时,笔记本中有一些“晃动”的报告。如果您注意到这一点,请尝试使用print('message', flush=True)