覆盖 Jupyter 输出小部件的字符串

问题描述

如何覆盖由 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一个极简示例,尚未收到答案。如果您需要更多上下文,请随时阅读该问题!

解决方法

感谢官方 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

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

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