PyCharm 2021.2 Help

Use interactive widgets

PyCharm supports interactive widgets that provide integration between Python code running in the notebook kernel and JavaScript running in the browser. Refer to the Jupyter widgets documentation for more details about the variety and specifics of interactive widgets.

To add an interactive widget to your notebook, first add a code cell. Press Alt + Shift + A (Windows) or ⌥ ⇧ A (macOS) to insert a new cell above the currently selected cell, or Alt + Shift + B (Windows) or ⌥ ⇧ B (macOS) to create a new cell below the selected cell. See Edit Jupyter notebook files for more details.

When editing code of an interactive widget, use code completion to facilitate adding constructs and quick fixes to add missing import statements.

To preview the widgets, you need to execute the corresponding code cell. You can see the values of the widget variables inlined in the editor and listed in the Variables tab of the Jupyter tool window.

example of two linked interactive widgets

In addition to creating code cells with interactive widgets, you can inject JavaScript calls into Python code cells and pass widget variables to the JavaScript code. Consider an example that passes the selected color value of the ColorPicker widget to the JavaScript call to paint the background of the document:

#%% from IPython import display from ipywidgets import widgets colorpicker = widgets.ColorPicker( concise=False, description='Pick a color', value='black', disabled=False ) display.display(colorpicker) #%% from IPython.core.display import Javascript color = colorpicker.value Javascript(""" let div = document.getElementById('color'); = "{}"; """.format(color))

When you select a color in the color picker and then execute the second code cell, the selected color is applied to the background of the notebook preview.

example of calling a JavaScript interactive widget from Python code

Handling security requirements

If you open any JavaScript code in a notebook file created outside of your project, that notebook is considered untrusted. According to the security model established for Jupyter notebooks, untrusted JavaScript code is never executed. That's why when you try to execute JavaScript in such a notebook, you will receive an error message: Notebook is not trusted. JavaScript hasn't been executed.

Select the Trusted checkbox on the Jupyter toolbar to explicitly allow executing JavaScript in your Jupyter notebook.

Making the JavScript code trusted
Last modified: 19 May 2021