How to make an ipywidgets Image clickable?
%%javascript
let kernel = IPython.notebook.kernel;
kernel.execute("on_image_click()");
or
can even get printed data back from python
%%javascript
let callback = {
iopub: {
// have a look at data on console for its structure
output: (data) => {console.log(data)}}
}
};
let kernel = IPython.notebook.kernel;
kernel.execute("on_image_click()", callback);
After playing around with this, the only way I could do it so far is by using some javascript... in the python code, I have something like:
from ipywidgets import Image
from IPython.display import display, Javascript
im = Image(value=open(filename, 'rb').read())
im.add_class('the_image_class')
def on_image_click():
#do something....
return
#Now, I wrote some javascript(jQuery) code like this...
js = ''' $(".the_image_class").on("click", function(e){
var kernel = IPython.notebook.kernel;
kernel.execute("on_image_click()");
});'''
#then, run the javascript...
display(Javascript(js))
Which is kind of missing the point of using the widgets entirely in python... Is there a better way to bind python functions to the widgets events, without javascript?
I find the other responses to be hacks (Injecting JavaScript on the page is not a good practice, and it might not work in JupyterLab).
You can have a look at ipyevents: https://github.com/mwcraig/ipyevents
It allows you to add event listeners to any widget, and it is developed by a core-ipywidgets maintainer.