I am trying to write a library as part of a JupyterLab extension that displays UI elements in the notebook output area using ipywidgets. As part of this, I want to add a new code cell in the notebook when a button is clicked. I tried using get_ipython() based methods in the event handler for the button but was not able to add a code cell. How can I add a new code cell from the event handler of a ipywidgets button?
kernels generally have no knowledge of the client running them, and can only do what the protocol provides.
ipylab exposes the command registry: of course this ties you more closely to jupyterlab. But If you’re already writing an extension, you could just rig up a custom event that did precisely what you wanted.
Thanks @bollwyvl for the solution. For now, I used the ipylab library to access the command registry and run a command to add the code cell. However, it’d be interesting to know the other approach you suggested - ‘rig up a custom event’ - is this the ipywidget event or the JupyterLab event? Could you elaborate a bit more on this or maybe point me to some example?
A widget can send custom kernel-side events which are received by the frontend. ipylab
actually is the example i’d provide, as it does this for running commands (client, kernel)… there are some focus
and blur
custom events in the future to core, though.
In a custom implementation, a WidgetView
knows its actual, concrete DOM node in the client. With that information, it could walk its parents and do something if it’s e.g. in a NotebookPanel
… that interface is also somewhat opaque, as it’s definitely possible to have the same logical WidgetModel
represented in multiple places, some not even attached to the parent (e.g. with Create View for Output).