3

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.

4
  • JavaScript running where? Node.js? A web browser? Commented 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. Commented Oct 9, 2015 at 0:58
  • @Quant Ok, but I am going to need a link or more information. Thanks! Commented Oct 9, 2015 at 17:04
  • @DougBlank could not add multi-line code snippet in the comment. I replied below with a short example. Commented Oct 9, 2015 at 17:08

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

And how exactly I get x_model and y_model variables passed to the function?
2

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

What does the Javascript side look like?
The value must be set on the widget backbone model. model.set('value', 17);
0

you can use this nootebook if you can install jupyter proxy server

https://github.com/gbrault/jpjwidgets

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.