简体   繁体   English

如何从 Jupyter 文本小部件获取鼠标选择的文本?

[英]How to get mouse selected text from Jupyter text widget?

I want to capture the mouse selected text from a jupyter text widget.我想从 jupyter 文本小部件中捕获鼠标选择的文本。

import ipywidgets as widgets
text = widgets.Textarea(
    value='Hello World',
    description='String:',
    disabled=False
)
display(text)

In the following example when World is selected and left click is complete then I want to capture the text highlighted. In the following example when World is selected and left click is complete then I want to capture the text highlighted.

在此处输入图像描述

With a JS you can add listener on select event of the original text widget.使用 JS,您可以在原始text小部件的select事件上添加侦听器。 Then the selected text is copied into a sel_text widget.然后将所选文本复制到sel_text小部件中。 Finally you can access it through the sel_text.value最后你可以通过sel_text.value访问它

import ipywidgets as widgets
from IPython.display import Javascript

ta_description = 'String:'
text = widgets.Textarea(
    value='Hello big World',
    description=ta_description,
    disabled=False
)
sel_text = widgets.Text(
    value='',
    description='selected text:',
    disabled=True
)
display(text, sel_text)

jscript = f'''

function put2widget(arg) {{
    var manager = window.IPython.WidgetManager._managers[0];
    var ta = manager.get_model('{sel_text.model_id}');
    ta.then(function(model) {{
        model.set('value', arg)
        model.save()
    }});
}}

function getSelection(event) {{
  const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd);
  put2widget(selection)

}}

const area = document.querySelectorAll('label[title="{ta_description}"]')[0].parentNode.getElementsByTagName('textarea')[0]
area.addEventListener("select", getSelection); 

'''

Javascript(jscript)

There no way to capture or print the mouse selected keyword in Jupyter.无法在 Jupyter 中捕获或打印鼠标选择的关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM