Say that there is a ipywidget created in IPython notebook, like so:
from ipywidgets import widgets
i = widgets.IntText()
Is there a way to set the value from Javascript? I suspect that I'll need to know some comm id of the widget. Or is there a better way to have a variable in Python that gets set from Javascript?
The use case is that I want to send a mouse click position (gotten via Javascript) position back to Python.
Thanks to SylvainCorlay and jasongrout on ipython gitter, they were able to talk me through this:
clicked = function (evt, x_model, y_model) {
var e = evt.srcElement.farthestViewportElement || evt.target;
var dim = e.getBoundingClientRect();
var x = evt.clientX - dim.left;
var y = evt.clientY - dim.top;
var manager = IPython.WidgetManager._managers[0];
var model_prom = manager.get_model(x_model);
model_prom.then(function(model) {
model.set('value', Math.round(x));
model.save_changes();
});
model_prom = manager.get_model(y_model);
model_prom.then(function(model) {
model.set('value', Math.round(y));
model.save_changes();
});
};
Where onclick is called with the event, and the Python x.model_id and y.model_id.
You can bind widget models on the JavaScript side using the ipython jslink widget.
from ipywidgets import IntText, IntSlider, jslink
from IPython.display import display
text, slider = IntText(), IntSlider()
link = jslink((text, 'value'), (slider, 'value'))
display(text, slider)
If you want a pure JavaScript solution, you can address the widget model from the widget manager using the widget id.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With