Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting text from Jupyter text widget?

I want to create an interactive Jupyter notebook. I'd like to have a Textarea, where if I enter some text, a function gets run on the text I entered. I'm trying:

text = widgets.Textarea(
    value='last',
    placeholder='Paste ticket description here!',
    description='String:',
    disabled=False
)
display(text)
text.on_displayed(show_matches(text.value))

Then I want to perform some magic with show_matches and display a pandas dataframe (diplay(df)). However, this only runs if I explicitly run the cell and then again only with the predefined last string. I want it to run whenever I finish writing in the text area, with the text I wrote. How can I do this (eg.: How can I bind the value of the Textarea to a Python variable and run a function whenever the value changes)?

like image 786
lte__ Avatar asked Dec 19 '22 03:12

lte__


2 Answers

If you want to use Text instead of Textarea you can connect a callback via the on_submit method. This gets executed once Enter is hit in the text field.

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

text = widgets.Text(
    value='last',
    placeholder='Paste ticket description here!',
    description='String:',
    disabled=False
)
display(text)

def callback(wdgt):
    # replace by something useful
    display(wdgt.value)

text.on_submit(callback)
like image 165
ImportanceOfBeingErnest Avatar answered Dec 27 '22 01:12

ImportanceOfBeingErnest


The previous answer works but you need to execute the cell again every time you update your text value. Here's another solution using interact.

Write your function and let the widget take in the argument with a textbox

@interact
def show_matches(text='last'):
    # do your thing with text and get the result
    display(result)

This way the widget knows to display result in realtime as you update your text value, no need to run the cell again and again.

like image 44
Logan Yang Avatar answered Dec 27 '22 02:12

Logan Yang