【问题标题】:Overwrite string of Jupyter Output widget覆盖 Jupyter 输出小部件的字符串
【发布时间】:2021-01-19 10:48:17
【问题描述】:

如何覆盖 Jupyter 输出小部件打印的字符串?

例如,我知道如何使用简单的print 语句来做到这一点:

from IPython.display import display, clear_output


fruits = ["apple", "orange", "kiwi"]

for fruit in fruits:
    clear_output()
    print(f"Do you like {fruit}s?")

产生我所期望的:为每个新的fruit 打印一次字符串,覆盖之前的字符串。在我的示例中,最后打印的语句是Do you like kiwis?

但我需要使用输出小部件而不是打印语句来做到这一点。 我试过了:

import ipywidgets as widgets


out = widgets.Output()

for fruit in fruits:
    out.clear_output()
    out.append_stdout(f"Do you like {fruit}s?")

out

我得到:Do you like apples?Do you like oranges?Do you like kiwis?,这不是我想要的!

我还尝试将out.clear_output() 放在append_stdout 之后,但我得到一个空行。在这种情况下,似乎每个字符串在打印新字符串之前实际上都被取消了,而且最后一个字符串也被取消了!

感谢任何建议!

最后说明: 此问题是来自another question 的极简示例,尚未收到答案。如果您需要更多上下文,请随时阅读该问题!

【问题讨论】:

    标签: python jupyter-notebook jupyter jupyter-lab jupyter-widget


    【解决方案1】:

    感谢官方ipywidgets 文档中的chapter on traitlets,我解决了这个极简示例。

    out = widgets.Output()
    
    for fruit in fruits_names:
        with out:
            out.clear_output()
            print(f"Do you like {fruit}s?")
    out
    

    我仍然不完全理解为什么这会按预期工作,而在 with 语句之外调用 out.clear_outputout.append_stdout 却没有!如果您有解释,请告诉我!

    我仍然对我的other bigger question 感兴趣。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-27
      • 1970-01-01
      • 1970-01-01
      • 2012-05-28
      • 2013-11-28
      • 2022-11-04
      • 1970-01-01
      • 2010-12-09
      相关资源
      最近更新 更多