Search code examples
pythononchangeobserversipywidgets

ipywidgets Text on_change is buggy refreshes while typing


I am using ipywidgets.Text and written a function that would run when the text has changed. that function is time-intensive. The Text takes integers up to 1000.

from ipywidgets import Text
a = Text(description = "Type here", placeholder = "integer: ex: 123")

def on_change(change):
    if change["new"]!= change["old"]:
        print(change)
        #some time intensive code
a.observe(on_change, names =["value"])

so, when I type say 123, the on_change function runs for 1,12 and 123(picture attached). enter image description here Can I somehow eliminate it running for 1 and 12?

One obvious idea is to keep an explicit button and run only when that is clicked.. but isn't there a better idea?


Solution

  • You can use continuous_update=False to your widget.

    a = Text(
        description = "Type here", 
        placeholder = "integer: ex: 123",
        continuous_update=False
    )
    

    Using this parameter your on_change function will receive the value only when the user: press enter or remove the focus from the input.