Jupyter ipython clear_output() 不再工作

问题描述 投票:0回答:1

使用 Jupyter 版本:7.1.2。 这个玩具示例不起作用:

import ipywidgets as widgets
from IPython.display import display, clear_output

def page_1():
    button = widgets.Button(description="Next")
    def next_button_clicked(b):
        clear_output(wait=True)
        page_2()
    button.on_click(next_button_clicked)
    display(button)

def page_2():
    text = widgets.HTML(value='<h2 style="text-align:center">HELLO</h2>')
    display(text)

page_1()

page_1 确实出现,但是当单击“下一步”按钮时,没有任何反应。 “next_button_clicked”函数被正确调用,如附加打印所示(为简洁起见,从公开的示例中删除)。

这个例子以前运行正常,我怀疑是Jupyter升级后出现的问题。

有人有想法吗?

python jupyter ipython ipywidgets
1个回答
0
投票

使用现代 Jupyter 技术中的当前 ipywidgets,您需要指定如何处理

page_2()
内容的去向。
这是一个基本的实现,可以尽可能少地调整您的代码:

import ipywidgets as widgets
from IPython.display import display, clear_output

out = widgets.Output()

def page_1():
    button = widgets.Button(description="Next")
    def next_button_clicked(b):
        clear_output(wait=True)
        page_2()
    button.on_click(next_button_clicked)
    display(button)

def page_2():
    with out:
        text = widgets.HTML(value='<h2 style="text-align:center">HELLO</h2>')
        display(text)


page_1()
out

已在 Jupyter Notebook 7.1 中测试并运行,按下按钮时,页面 2 HTML 将按指示显示在中心。
您会注意到我添加了

out
并使用上下文管理器将第 2 页的内容定向到它。

在 Jupyter Notebook 7.1 中运行代码,按下按钮时没有看到任何反应。 但是,在 JupyterLab 中运行代码时,单击“下一步”按钮后,我会看到第 2 页的内容转到日志控制台。(您可以在临时 JupyterLab 会话中尝试此操作,无需在计算机上安装任何内容,通过单击此处启动会话,然后从启动器面板打开一个新笔记本。Ipywidgets 已安装在那里。)

这是 ipywidgets 输出未被处理的症状。请参阅此处的示例

由于您在 JupyterLab 中使用 ipywidgets 时获得的额外反馈,我建议您在对 ipywidgets 进行故障排除时可能会想要在 JupyterLab 中工作。据我所知,Jupyter Notebook 以文档为中心,不会公开日志控制台。

您可能希望更好地处理

page_2()
,如果有时间,我会尝试返回此处添加看起来更好的建议。

© www.soinside.com 2019 - 2024. All rights reserved.