How to extract text from ipwidgets Text widget

Question:

The documentation for this is very cumbersome and time-consuming. I need a simple basic Hello World example to extract a simple text from a text box

from ipywidgets import interact, widgets
from IPython.display import display

dossier_number_widget = widgets.Text(
    value='EP23210283',
    placeholder='EP23210283',
    description='Dossier Number:',
    disabled=False,
    continuous_update=True
)
display(dossier_number_widget)

def callback(wdgt):
    print(wdgt) # it doesn't print
    display(wdgt) # it doesn't display
    print(wdgt.value) # it doesn't print
    display(wdgt.value) # it doesn't display

dossier_number_widget.observe(callback, 'value')

It’s not working, what am I doing wrong?

Other examples here on SO mention on_submit but this method is deprecated

I tried with a button with no result, it simply doesn’t print the result

from ipywidgets import interact, widgets
from IPython.display import display

submit_button=widgets.Button(description='Submit',button_style='success')
dossier_number_widget = widgets.Text(
    value='EP23210283',
    placeholder='EP23210283',
    description='Dossier Number:',
    disabled=False,
    continuous_update=False
)

def on_button_clicked(wdgt):
    print(dossier_number_widget.value) # it doesn't print
    display(dossier_number_widget.value) # it doesn't display

submit_button.on_click(on_button_clicked)

display(dossier_number_widget, submit_button)

Answers:

Here is an example of extracting text from a text widget and reacting to it to give the user feedback:

from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets

text_input = widgets.Text(
        value="",
        description="Enter text here:",
        style={"description_width": "initial"},
        layout=widgets.Layout(width='70%'), 
    )

def f(x):
    if "Hello World" in x:
        return "WHAT YOU TYPED CONTAINS MY FAVORITE PHRASE! YOU DID IT!!"
    elif x != '':
        return (f"I see you typed: {x}. You haven't typed my favorite phrase yet.")
    else:
        return x

interact(f, x=text_input);

It mainly is adapted from a code block I shared here in reply to ‘Jupyter Widgets Formatting’ and the ipywidgets documentation on interact().

You’ll see that it doesn’t build on your example that you stated the following about, "It’s not working, what am I doing wrong?". Note, that your post doesn’t include what you expected to happen or how you wanted to extract and do something leaving a lot to the imagination and making it difficult to give reasonable answers based on your provided code. Please read How do I ask a good question? for next time. Especially the sections and links therein under sections about ‘on-topic and suitable’ and ‘Help others reproduce the problem’.

Additional resources

For additional help, see:

Answered By: Wayne