The above example suggests the direct use of print()
which isn’t handled well by ipywidgets running in current Jupyter flavors.
Proposed options that work in all current Jupyter tech
The use of print()
is not easily compatible with ipywidgets use in Jupyter Notebook 7+. With current JupyterLab, the print()
will go to the Log console, see here for more about that.
Therefore, to have something that works in the output area of any flavor current Jupyter tech, limiting lines and complexity, I’d propose you change that to add handling of changes with a ‘status’ output that can be updated because a DisplayHandle
has an update()
method:
import ipywidgets as widgets
from IPython.display import display, HTML
text_input = widgets.Text(
value='', # Initial
description='Type here:', # Label for the text input
disabled=False # to be editable
)
# Function to handle changes in the text input
def on_text_change(change):
if change['type'] == 'change' and change['name'] == 'value':
status_output.update(HTML(f"You entered: {change['new']}"))
status_output = display(HTML("STATUS WILL UPDATE HERE"), display_id=True)
# Observe changes in the text input widget
text_input.observe(on_text_change, names='value')
display(text_input)
That above requires the least change from darktrender’s code. The status_output
related code and the addition of HTML
to the end of the from IPython.display import
-line is the only real changes needed from darktrender’s code.
Alternative option that can run in either Jupyter tech currently & retains use of print()
If you introduce a context manager to handle print()
going to output , like illustrated here and elsewhere in the ipywidget’s documentation, you can still use print()
and get it to show in the cell’s output area. Starting with the darktrender’s code, you’d end up with something like the following that can run in either Jupyter tech:
import ipywidgets as widgets
from IPython.display import display
output = widgets.Output()
text_input = widgets.Text(
value='', # Initial
description='Type here:', # Label for the text input
disabled=False # to be editable
)
# Function to handle changes in the text input
def on_text_change(change):
if change['type'] == 'change' and change['name'] == 'value':
with output:
output.clear_output() # from 'Output widgets: leveraging Jupyter’s display system' https://ipywidgets.readthedocs.io/en/latest/examples/Output%20Widget.html
print(f"You entered: {change['new']}")
# Observe changes in the text input widget
text_input.observe(on_text_change, names='value')
display(output, text_input)
While not much more is needed compared to the option above, the addition of the output
widget and wrapping the print statements in the with output
context results definitely becoming more complex than darktrender’s code.