ipywidgets clear_output () не работает во второй раз, когда он используется - PullRequest
1 голос
/ 14 октября 2019

У меня странное поведение с виджетом 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 info:

Информация о сервере: Вы используете ноутбук 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.

Спасибо за помощь!

1 Ответ

1 голос
/ 14 октября 2019

Кажется, это связано с использованием append_stdout вместо диспетчера контекста. Вероятно, проблема с буферизацией.

Тем временем вы можете сделать:

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
...