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.
-
JavaScript running where? Node.js? A web browser?Pointy– Pointy2015年10月09日 00:50:28 +00:00Commented Oct 9, 2015 at 0:50
-
IPython notebooks run with a frontend in the browser, and a backend on the server. I'm looking for a way for Javascript in the browser to set the value of the traitlet so that the value can be accessed in Python on the server.Doug Blank– Doug Blank2015年10月09日 00:58:00 +00:00Commented Oct 9, 2015 at 0:58
-
@Quant Ok, but I am going to need a link or more information. Thanks!Doug Blank– Doug Blank2015年10月09日 17:04:58 +00:00Commented Oct 9, 2015 at 17:04
-
@DougBlank could not add multi-line code snippet in the comment. I replied below with a short example.Quant– Quant2015年10月09日 17:08:53 +00:00Commented Oct 9, 2015 at 17:08
3 Answers 3
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.
1 Comment
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.
2 Comments
model.set('value', 17);you can use this nootebook if you can install jupyter proxy server