LoginSignup
8
9

More than 5 years have passed since last update.

jupyterでhtml-javascript側の値を取得するメモ

Last updated at Posted at 2016-11-06

やりたいこと

jupyter上でhtml-javascriptを動かして、その結果の値をpython側に受け渡して使いたい
(例:javascript上でお絵かきした座標を使ってpython側で計算させたいなど)
と思い調べているとCustom-Widgetというものがあるようで試してみました。

使用例

以下のものはhtmlのフォームを表示させ、その中に入力したものをpython側に受け渡して表示しています。
こちらの例を少し改造していますが、慣れないjavascriptを使っているのでもっといい方法があるかもしれません。

無題の図形描画.png

ソース

  • html作成
%%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);//ここでフォーム内のテキストを取得
            this.touch();
        },
    });
    return {
        HelloView : HelloView
    };
});
</script></body></html>
  • 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#ここで一度ウイジェットを作る必要がある
  • フォーム内の値を取得(取得までにはわずかな時間がかかるので、直後に値を表示させると更新されていない)
my_widget.value += 'w'#valueに[w]を追加することで、無理やり値を変えて、同期イベントを起こし、フォーム内の値を取得
  • フォーム内の値を表示
print(my_widget.html_form)#フォーム内の値を表示
8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9