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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With