Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an ipywidgets Image clickable?

I would like to make an Image instance in a jupyter notebook to respond to click events - how can we do this? I also want to be able to identify the image that was clicked. It is simple to do so with buttons but not with images.

like image 534
Dror Hilman Avatar asked Feb 02 '17 09:02

Dror Hilman


People also ask

How do you interact in a Jupyter Notebook?

At the most basic level, interact autogenerates UI controls for function arguments, and then calls the function with those arguments when you manipulate the controls interactively. To use interact , you need to define a function that you want to explore. Here is a function that returns its only argument x .

How do Ipywidgets work?

Ipywidgets provides a list of functions that can let us create widgets UI for any of our existing functions. It'll create widgets by itself by looking at the parameters of functions and creating widgets UI with all parameters represented as one widget. It's a very good way to start using ipywidgets.


2 Answers

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?

like image 197
Dror Hilman Avatar answered Oct 15 '22 03:10

Dror Hilman


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.

like image 30
Martin Renou Avatar answered Oct 15 '22 04:10

Martin Renou