Connecting a click event on a widget to a function. #3680
-
Is it possible to connect a function to a click event on a specific widget? In particular, I am interested in linking a function execution to double-clicking on a particular Apologies if this is an obvious question, I could not find an answer after a reasonably thorough search of docs / issues but I may be looking for the wrong thing! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
If it's a specific widget you want to do this for, you could subclass that widget and handle it from there, adding your own from __future__ import annotations
from dataclasses import dataclass
from textual import on
from textual.app import App, ComposeResult
from textual.events import Click
from textual.message import Message
from textual.widgets import Input, Log
class ClickableInput(Input):
@dataclass
class Clicked(Message):
input: ClickableInput
def _on_click(self, _: Click) -> None:
self.post_message(self.Clicked(self))
class InputClickApp(App[None]):
def compose(self) -> ComposeResult:
yield ClickableInput()
yield Log()
@on(ClickableInput.Clicked)
def log_click(self, event: ClickableInput.Clicked) -> None:
self.query_one(Log).write_line(f"{event!r}")
if __name__ == "__main__":
InputClickApp().run() More generally, you could use from textual.app import App, ComposeResult
from textual.events import Click
from textual.widgets import Input, Label, Button
class ClickAnywhereApp(App[None]):
def compose(self) -> ComposeResult:
for n in range(10):
yield Input(id=f"input-{n}")
yield Label(f"Label {n}", id=f"label-{n}")
yield Button(f"Button {n}", id=f"button-{n}")
async def _on_click(self, event: Click) -> None:
self.notify(f"{self.get_widget_at(event.screen_x, event.screen_y)[0]}")
if __name__ == "__main__":
ClickAnywhereApp().run() You'll always get a notification from the screen and the labels, but never from the But, if as you say:
then you could roll your own subclass of |
Beta Was this translation helpful? Give feedback.
-
Thanks a lot @davep for the detailed and very prompt response! I will try this out today and let you know if anything comes up. Cheers! |
Beta Was this translation helpful? Give feedback.
-
Thanks @davep works like a dream! I had one question, I see it is not necessary to also call the method on the super class e.g. |
Beta Was this translation helpful? Give feedback.
If it's a specific widget you want to do this for, you could subclass that widget and handle it from there, adding your own
Clicked
message. For example: