首页 > 解决方案 > 如何在 Jupyter 笔记本中将 HTML 元素与 Python 函数链接?

问题描述

我编写了显示自定义右键菜单的 JavaScript 代码。

我想知道如何在我的菜单项被点击时触发 Python 函数。这些菜单项是嵌套在具有 menu 类的 div 下的 div,因此它是我的 HTML 正文部分中的唯一元素。

我使用的环境是 Jupyter Notebook。笔记本。

import jinja2
from bokeh.embed import components

template = jinja2.Template("""
<!doctype html>

<html>
    <head>
        <script>
            src="http://cdn.pydata.org/bokeh/dev/bokeh-0.13.0.min.js"
            var menuDisplayed = false;
            var menuBox = null;
           
            window.addEventListener("contextmenu", function() {
                var left = arguments[0].clientX;
                var top = arguments[0].clientY;
               
                menuBox = window.document.querySelector(".menu");
                menuBox.style.left = left + "px";
                menuBox.style.top = top + "px";
                menuBox.style.display = "block";
               
                arguments[0].preventDefault();
               
                menuDisplayed = true;
            }, false);
           
            window.addEventListener("click", function() {
                if(menuDisplayed == true){
                    menuBox.style.display = "none";
                }
            }, true);
        </script>
        <style>
            .menu
            {
                width: 150px;
                box-shadow: 3px 3px 5px #888888;
                border-style: solid;
                border-width: 1px;
                border-color: grey;
                border-radius: 2px;
                padding-left: 5px;
                padding-right: 5px;
                padding-top: 3px;
                padding-bottom: 3px;
                position: fixed;
                display: none;
            }
           
            .menu-item
            {
                height: 20px;
            }
           
            .menu-item:hover
            {
                background-color: #6CB5FF;
                cursor: pointer;
            }
        </style>
    </head>
    <body>
        <div class="menu">
            <div class="menu-item">Add Node</div>
            <div class="menu-item">Delete Node</div>
            <div class="menu-item">Update Node</div>
        </div>
    </body>
</html>
""")


 

标签: javascriptpythonhtmljqueryflask

解决方案


我认为您将通过以下示例轻松地对此有清晰的理解和清晰度:

// %%javascript
window.executePython = function(python) {
    return new Promise((resolve, reject) => {
        var callbacks = {
            iopub: {
                output: (data) => resolve(data.content.text.trim())
            }
        };
        Jupyter.notebook.kernel.execute(`print(${python})`, callbacks);    
    });
}



// Use it in any Jupyter JS/HTML cell like this
%%javascript
window.executePython("1 + 1")
    .then(result => console.log(result)); // Logs 2

// You can access any defined object/method in the notebook
// I suggest writing a function that returns your data as JSON and just calling the function.

推荐阅读