With a JS you can add listener on select
event of the original text
widget. Then the selected text is copied into a sel_text
widget. Finally you can access it through the 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)