簡體   English   中英

如何使 ipywidgets 圖像可點擊?

[英]How to make an ipywidgets Image clickable?

我想在 jupyter 筆記本中創建一個 Image 實例來響應點擊事件 - 我們該怎么做? 我還希望能夠識別被點擊的圖像。 使用按鈕很簡單,但使用圖像則不然。

在玩弄這個之后,到目前為止我能做到的唯一方法是使用一些 javascript... 在 python 代碼中,我有類似的東西:

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))

哪一種錯過了完全在 python 中使用小部件的要點......是否有更好的方法將 python 函數綁定到小部件事件,而無需 javascript?

%%javascript
let kernel = IPython.notebook.kernel;
kernel.execute("on_image_click()");

或者

甚至可以從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);

我發現其他響應是 hacks(在頁面上注入 JavaScript 不是一個好習慣,它可能在 JupyterLab 中不起作用)。

你可以看看ipyevents: https : //github.com/mwcraig/ipyevents

它允許您向任何小部件添加事件偵聽器,它由核心 ipywidgets 維護者開發。

我不是直接回答這個問題,但我在解決類似問題時偶然發現了這個問題,也許我的解決方案對某人有用。 我想在單擊時在 jupyter 筆記本單元格中循環圖像。 實際上,我可以接受任何交互,例如按鈕甚至重新運行單元格。 我的目標是最少的代碼,因為這是一個演示文稿,我不想用 30 行 javascript 來打擾我的觀眾,只是為了循環一些圖像。 所以這是在 Shift+Enter 上循環圖像的解決方案。

# Import and set a counter in one cell
from IPython.display import Markdown; slide = 0

# Loop images in a different cell
if not os.path.isfile('img{}.jpg'.format(slide)): slide = 0
slide +=1; Markdown("""<img src="img{}.jpg" style="height:100px">""".format(slide-1))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM