2

我在使用Output来自ipywidgets. 我在 jupyter 笔记本中使用以下代码复制它:

import ipywidgets as widgets

def clear_output():
    change_output_button = widgets.Button(description="Change output?")
    the_output = widgets.Output()
    clear_output_widget = widgets.VBox([change_output_button, the_output])
    clear_output_widget.click_count = 0

    def button_clicked(_button):
        clear_output_widget.click_count += 1
        the_output.clear_output()
        the_output.append_stdout(f"button clicked {clear_output_widget.click_count} times.")

    change_output_button.on_click(button_clicked)

    return clear_output_widget

在另一个单元格中,我输入

clear_output()

它按预期显示按钮。

以下是我得到的输出序列:

  • 点击 1
button clicked 1 times.
  • 点击 2
button clicked 1 times.button clicked 2 times.
  • 点击 3
button clicked 3 times.
  • 点击 4
button clicked 4 times.

等等...

我不明白点击 2 的行为。难道我做错了什么?

以下是我关于 Jupyter Notebook的信息:

服务器信息:您正在使用 Jupyter 笔记本。

笔记本服务器的版本是:6.0.1 服务器运行在这个版本的 Python 上:

Python 3.7.4 (default, Aug  9 2019, 18:22:51) [MSC v.1915 32 bit (Intel)]

当前内核信息:

Python 3.7.4 (default, Aug  9 2019, 18:22:51) [MSC v.1915 32 bit (Intel)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.8.0 -- An enhanced Interactive Python. Type '?' for help.

谢谢你的帮助!

4

1 回答 1

3

这似乎是由于使用append_stdout而不是上下文管理器。可能是缓冲问题。

In the meantime you can do:

import ipywidgets as widgets


def clear_output():
    change_output_button = widgets.Button(description="Change output?")
    the_output = widgets.Output()
    clear_output_widget = widgets.VBox([change_output_button, the_output])
    clear_output_widget.click_count = 0

    def button_clicked(_button):
        clear_output_widget.click_count += 1
        the_output.clear_output()
        with the_output:
            print(f"button clicked {clear_output_widget.click_count} times.")


    change_output_button.on_click(button_clicked)

    return clear_output_widget
于 2019-10-14T17:38:41.120 回答