How to make actions to copy and paste selected text in Textarea? #4051
-
from textual import on, work
from textual.app import App, ComposeResult, events
from textual.widgets import *
from textual.binding import Binding
import pyperclip
class ScriptApp(App):
BINDINGS = [
Binding("ctrl+p", "copy_to_clipboard"),
Binding("ctrl+v", "paste_from_clipboard"),
]
def compose(self) -> ComposeResult:
yield TextArea("Test Sceniaro 1:", id="textarea-1")
yield TextArea("Test Sceniaro 1:", id="textarea-2")
yield Output()
@work(exclusive=True, thread=True)
def action_copy_to_clipboard(self) -> None:
self.query_one(Output).begin_capture_print()
text_to_copy = self.query_one(TextArea).selected_text
pyperclip.copy(text_to_copy)
@work(exclusive=True, thread=True)
def action_paste_from_clipboard(self) -> None:
self.query_one(Output).begin_capture_print()
self.query_one(TextArea).replace(
pyperclip.paste(),
self.query_one(TextArea).selection.start,
self.query_one(TextArea).selection.end,
)
class Output(RichLog):
def __init__(self) -> None:
super().__init__(highlight=True, markup=True)
@on(events.Print)
def on_print(self, event: events.Print) -> None:
if event.text.strip():
self.write(event.text)
app = ScriptApp()
if __name__ == "__main__":
app.run()Run this app, it has two Textarea widgets. The actions fail since |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 8 replies
-
|
Your question doesn't really have anything to do with You'll notice you actually gave your self.query_one("#textarea-1", TextArea) |
Beta Was this translation helpful? Give feedback.
I think I understand the confusion now. The
query_onemethod just gets a widget, it doesn't know what widget is currently focused.You could check if the
TextAreais focused like @Zaloog suggested.But actually if this binding shouldn't do anything if a different type of widget is focused, wouldn't it make more sense to add the binding to the TextArea, rather than the App?