5

Using Python 3.7 in a Jupyter notebook, the code below shows a text entry field that triggers the handle_submit function to print out some output. In this example 40 repetitions of the input.

from ipywidgets import widgets
from IPython.display import display

text = widgets.Text()
display(text)

def handle_submit(sender):
    print('\n'.join([text.value] * 40 ))   

text.on_submit(handle_submit)

Running this code displays a text box.

If you enter text in the box and press Enter, the handle_submit function is run and the "result" is printed.

This can be used multiple times, but all old output is kept. So after using the entry field a couple of times you need to scroll endlessly to get to the new result.

Is there a command to clear the cell output before printing new output from the handle_submit function? Unlike this example, the output length is not fixed, so the solution should handle differently sized outputs.

576i
  • 7,579
  • 12
  • 55
  • 92

1 Answers1

8

By creating an Output widget, you can print to this widget the same way as a cell output. You also have the option to call clear_output() in a context manager to, well, clear the output.

I've coded this up so the output is cleared every time new input is submitted, but there's no reason why you couldn't hook a button up to run clear_output() to do this manually.

from ipywidgets import widgets
from IPython.display import display, clear_output

text = widgets.Text()
display(text)
output = widgets.Output()
display(output)

def handle_submit(sender):
    with output:
        clear_output()
        print('\n'.join([text.value] * 40 ))   

text.on_submit(handle_submit)
ac24
  • 5,325
  • 1
  • 16
  • 31