简体   繁体   中英

Jupyter: how to print to cell in function, called back from JavaScript?

my question is about interactive Jupyter notebooks.

I want to display JavaScript button and print something to cell as result of button click.

We can do this easely with ipywidgets:

def OnClick(b=None): print 'qq'
b = widgets.Button(description='Button')
b.on_click(OnClick)
display(b)

But when we jumps to pure JavaScript things goes wrong. Ie I have JavaScript Button, in on_click() event handler I use kernel interaction like:

var kernel = IPython.notebook.kernel;
kernel.execute('onClick()');         

Callback is called successfuly (I checked by beep), but print produce no output in cell, where by button is displayed. So I suppose there should be some magic (like everyting in Python world!) to acceess print area, could you please help me to cast it?

The key is to use Output widget

from ipywidgets import widgets
from IPython.display import display, HTML

out = widgets.Output()

def OnClick():
    with out:
        print 'QQQ'

display(HTML('<a onclick="IPython.notebook.kernel.execute(\'OnClick()\')">Click!</a>'))
display(out)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM