Working on Jupyter Version: 7.1.2. This toy example does not work :
import ipywidgets as widgets
from IPython.display import display, clear_output
def page_1():
button = widgets.Button(description="Next")
def next_button_clicked(b):
clear_output(wait=True)
page_2()
button.on_click(next_button_clicked)
display(button)
def page_2():
text = widgets.HTML(value='<h2 style="text-align:center">HELLO</h2>')
display(text)
page_1()
page_1 does appear, but when clicking on the "Next" button, nothing happens. The "next_button_clicked" function is properly called, as indicated by additional prints (removed from the exposed example for brevity).
This example used to work properly before, and I suspect the problem appeared after a Jupyter upgrade.
Does somebody have an idea?
With current ipywidgets in modern Jupyter tech, you need to specify how to handle where the page_2()
content goes.
Here is a basic implementation that adjusts your code about as little as possible:
import ipywidgets as widgets
from IPython.display import display, clear_output
out = widgets.Output()
def page_1():
button = widgets.Button(description="Next")
def next_button_clicked(b):
clear_output(wait=True)
page_2()
button.on_click(next_button_clicked)
display(button)
def page_2():
with out:
text = widgets.HTML(value='<h2 style="text-align:center">HELLO</h2>')
display(text)
page_1()
out
That has been tested and run in Jupyter Notebook 7.1 and when pressing the button, the page 2 HTML is displayed in the center as directed.
You'll note that I have added out
and using a context manager to wrap the directing of the content of page 2 to it.
Running your code in Jupyter Notebook 7.1, I see nothing happen when I press the button. However, when running your code in JupyterLab, upon clicking the 'Next' button, I see the content of page 2 go to the Log Console. (You can try this in a temporary JupyterLab session without needing to install anything on your computer, by clicking here to launch a session and then open a new notebook from the launcher panel. Ipywidgets is already installed there.)
That is symptomatic of ipywidgets output not being handled. See an example here and another here.
Because of this extra feedback you get when working with ipywidgets in JupyterLab, I suggest you are probably going to want to work in JupyterLab when troubleshooting ipywidgets. Jupyter Notebook is document-centric and doesn't expose the log console as far as I know.
Given the title about clear_output()
, I was planning to add handling transitions that involved that; however, before I could the OP added a great example as an answer. Those curious more about clear_output()
and looking for additional related code can see here and references therein.