【问题标题】:why cannot I print in jupyter lab using ipywidgets class?为什么我不能在 jupyter lab 中使用 ipywidgets 类打印?
【发布时间】:2021-06-16 15:33:12
【问题描述】:

我使用 ipyvuetify 库在 Jupyter 环境中创建仪表板。该库工作得非常好,但我在 Jupyterlab 上苦苦挣扎,瞧,在这个问题上似乎有相同的行为:

假设我想创建一个小部件,当点击时打印一条消息:

import ipyvuetify as v 

class Test(v.Btn):
    
    def __init__(self, msg):
        
        self.msg = msg
        
        super().__init__(children=['click'])
        
        self.on_event('click', self._on_click)
        
    def _on_click(self, widget, event, data):
        
        print(self.msg)
        
        return
    
btn = Test(toto)
btn

如果我从 Jupyter Notebook 运行此代码,一切正常,msgbtn 单元格输出之后打印。如果我在 Jupyterlab 中做同样的事情,打印语句会在日志中结束。

现在如果运行:

btn._on_click(None, None, None)

msg 打印在 Jupyterlab 和 Jupyter Notebook 中。

有人能解释一下为什么会出现行为差异,以及如何确保我的打印语句最终出现在主工作流程中而不是日志中吗?

【问题讨论】:

    标签: python vuetify.js jupyter jupyter-lab ipywidgets


    【解决方案1】:

    确实,JupyterLab 实现了与 Jupyter Notebook 不同的机制来捕获输出,通过 ipywidget 的 Output 小部件

    import ipyvuetify as v
    import ipywidgets as w
    
    class Test(v.Btn):
        output = w.Output()
        def __init__(self, msg):
            
            self.msg = msg
            
            super().__init__(children=['click'])
            
            self.on_event('click', self._on_click)
            
        @output.capture()
        def _on_click(self, widget, event, data):
            
            print(self.msg)
            
            return
    
        def _ipython_display_(self):
            display(super(),self.output)
    
        
    btn = Test('toto')
    btn
    

    Ipywidget documentation_on_click 的输出通过使用上下文管理器 with self.output: over print()capture 装饰器定向到 output,以捕获由 _on_click 生成的所有输出函数(上面的例子)。

    https://github.com/jupyterlab/jupyterlab/issues/3151#issuecomment-339476572中的一些解释:

    我们在经典笔记本中整合了向后兼容的解决方法,但在 jupyterlab 中没有。部分原因是在 jlab 中编写笨拙的解决方法要困难得多:)。

    本质上,技术问题是小部件通信消息来自 客户端的浏览器需要将输出回调设置为 将输出附加到当前输出区域 - 但 IIRC 很难从 mime 渲染器获取包含它的输出区域的句柄。

    【讨论】:

      猜你喜欢
      • 2018-09-07
      • 2022-06-11
      • 2019-04-27
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 2016-02-01
      • 2022-01-25
      相关资源
      最近更新 更多