0

How do I overwrite a string that is printed by Jupyter Output widget?

For instance, I know how to do that using simple print statements:

from IPython.display import display, clear_output


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

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

Produces what I would expect: the string is printed once for each new fruit, overwriting the previous string. In my example, the last printed statement is Do you like kiwis?.

But I need to do that with Output widget instead of print statement. I tried:

import ipywidgets as widgets


out = widgets.Output()

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

out

And I get: Do you like apples?Do you like oranges?Do you like kiwis?, which is not what I want!

I also tried placing out.clear_output() after the append_stdout, and I get a blank line. It seems like in this case each string is actually cancelled before the new one is printed, but also the last string is cancelled!

I appreciate any suggestions!

Final note: This question is a minimalist example from another question, that has not yet received an answer. If you need more context, feel free to also read that question!

Enrico Gandini
  • 855
  • 5
  • 29

1 Answers1

0

I solved this minimalist example, thanks to the chapter on traitlets of the official ipywidgets documentation.

out = widgets.Output()

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

I still do not perfectly understand why this works as expected, whereas calling out.clear_output and out.append_stdout outside of a with statement did not! Please let me know if you have an explanation!

I am also still interested in my other bigger question.

Enrico Gandini
  • 855
  • 5
  • 29