I want to run html-javascript on jupyter and pass the resulting value to python for use (Example: I want to calculate on the python side using the coordinates drawn on javascript, etc.) When I was thinking about it, I found that there was Custom-Widget and tried it.
The following one displays the html form, and the one entered in it is passed to the python side and displayed. [This example](https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Custom.html#Building-a-Custom-Widget --- Date-Picker) is slightly modified, but I'm using javascript, which I'm not used to, so there may be a better way.
--html creation
%%html
<!DOCTYPE html><html lang="ja">
<head><mata charset="utf-8"/><title>widget test</title></head><body>
<form name="js"><input type="text" name="txt_form" value=""><br></form><script>
require.undef('hello');
define('hello', ["@jupyter-widgets/base"], function(widgets) {
var HelloView = widgets.DOMWidgetView.extend({
render: function() {
this.model.on('change:value', this.value_changed, this);
},
value_changed: function() {
this.model.set('html_form', document.js.txt_form.value);//Get the text in the form here
this.touch();
},
});
return {
HelloView : HelloView
};
});
</script></body></html>
--Create ipywidgets
import ipywidgets as widgets
from traitlets import Unicode
class HelloWidget(widgets.DOMWidget):
_view_name = Unicode('HelloView').tag(sync=True)
_view_module = Unicode('hello').tag(sync=True)
value = Unicode('Hello World!').tag(sync=True)
html_form = Unicode('').tag(sync=True)
my_widget = HelloWidget()
my_widget#You need to make a widget here
--Get the value in the form (It takes a little time to get it, so if you display the value immediately after it, it will not be updated)
my_widget.value += 'w'#to value[w]By adding, forcibly change the value, raise a synchronization event, and get the value in the form
--Display values in the form
print(my_widget.html_form)#Show values in the form
Recommended Posts