从 Jupyter 文本小部件获取文本?

Getting text from Jupyter text widget?

我想创建一个交互式 Jupyter 笔记本。我想要一个 Textarea,如果我在其中输入一些文本,一个函数会在我输入的文本上获取 运行。我正在尝试:

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

然后我想用 show_matches 执行一些魔术并显示 pandas 数据帧 (diplay(df))。但是,如果我明确地 运行 单元格然后再次仅使用预定义的 last 字符串,则这只有 运行s。每当我在文本区域中用我写的文本完成书写时,我希望它 运行 。我该怎么做(例如:如何在值更改时将 Textareavalue 绑定到 Python 变量和 运行 函数)?

如果您想使用 Text 而不是 Textarea,您可以通过 on_submit 方法连接回调。一旦在文本字段中按下 Enter,就会执行此操作。

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)

之前的答案有效,但每次更新文本值时都需要再次执行单元格。这是另一个使用 interact.

的解决方案

编写您的函数并让小部件通过文本框接收参数

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

这样小部件就会知道在您更新文本值时实时显示结果,无需一次又一次地 运行 单元格。