【问题标题】:Import a iPython Custom Widget Function (File Structure?)导入 iPython 自定义小部件函数(文件结构?)
【发布时间】:2025-11-30 01:55:01
【问题描述】:

我正在尝试按照this 示例和this 教程制作一个D3 小部件,该小部件在调用函数时向小部件显示D3 HTML 代码。我能够让它发挥作用within the notebook cells itself using %%javascript,但这对于最终用户来说会很混乱。

如何将 Python D3Widget 类定义和 Javascript D3View 渲染代码移动到外部文件,以便用户可以简单地导入文件并调用函数?

我希望最终结果看起来像 this,用户可以在其中简单地导入一个函数并调用它。

【问题讨论】:

    标签: javascript python d3.js ipython jupyter


    【解决方案1】:

    组织你的代码

    在您的笔记本根文件夹中为您的新小部件创建一个包。例如,您可以使用以下目录结构:

    helloworld/
    
        __init__.py
        helloworld_widget.py
    
        helloworldjs/
            helloworld.view.js
    
            css/
                helloworld.css
    

    对服务器端进行编程

    在 helloworld/helloworld_widget.py 中,放置你的 Python 类:

    from ipywidgets import widgets
    from traitlets import Unicode
    
    class HelloWorldWidget(widgets.DOMWidget):
        _view_module = Unicode("nbextensions/helloworld/helloworld_view", sync=True)
        _view_name = Unicode('HelloWorldView', sync=True)
    

    这就是你的 python 代码。

    创建 Javascript 视图

    在 helloworld/helloworldjs/helloworld.view.js 中为您的客户端编程:

    define(["nbextensions/widgets/widgets/js/widget"], function(widget) {
    
        var HelloWorldView = widget.DOMWidgetView.extend({
    
            render: function(){
                this.$el.text("Hello world");
            },
        });
    
        return {HelloWorldView: HelloWorldView}
    });
    

    很简单,不是吗?最后但并非最不重要的...

    将客户端部署到笔记本的扩展文件夹

    为此,您可以在 init.py 中编写一个函数,并在每次修改 Javascript 视图中的内容时在笔记本中执行它。

    我用这个和下面的很相似:

    def notebook_install(overwrite=True, user=True):
        import os
        from notebook import install_nbextension
        from notebook.services.config import ConfigManager
        from IPython.display import display, Javascript
    
        js_path = os.path.join( os.path.dirname(__file__), 'helloworldjs')
        install_nbextension(js_path, overwrite=overwrite,
                            symlink=False, verbose=0, user=user)
    

    现在您应该能够在笔记本中执行以下操作:

    from helloworld.helloworld_widget import HelloWorldWidget
    hello = HellowWorldWidget()
    hello
    

    享受吧!

    仔细阅读这篇文章也应该有所帮助:https://carreau.gitbooks.io/jupyter-book/content/notebook-extensions.html

    【讨论】: