#!/usr/bin/env python # coding: utf-8 # In[1]: import ipywidgets as widgets from IPython.display import display, clear_output print("Before Widget") output_counter = 0 out = widgets.Output(layout={'border': '1px solid black'}) def button_on_click(b): out.clear_output() with out: print("Inside Widget") global output_counter output_counter += 1 print(f'Outside Widget {output_counter}') btn = widgets.Button(description="Test") btn.on_click(button_on_click) Container = widgets.VBox(children=[btn]) display(Container,out) print('After Display') # In[2]: # create an output area to display detached widget output comm_out = widgets.Output() display(comm_out) # send detatched output created during comm msgs to our output area ip = get_ipython() original_comm_msg_handler = ip.kernel.shell_handlers["comm_msg"] def captured_comm_msg(*args, **kwargs): with comm_out: return original_comm_msg_handler(*args, **kwargs) ip.kernel.shell_handlers["comm_msg"] = captured_comm_msg # In[3]: print(f"{output_counter=}") # comm_out references the global namespace, so redefining it changes the destination # for future executions comm_out = widgets.Output() comm_out