How do I create an interactive button? #28
Unanswered
ethansocal
asked this question in
Q&A
Replies: 2 comments 2 replies
-
|
Documentation is coming, but the basic principle is you have a widget with an on_click method and you emit a message. from textual.message import Message
class ButtonPressed(Message, bubble=True):
pass
class Button(Widget):
async def on_click(self, event: events.Click) -> None:
await self.emit(ButtonPressed(self))Then in the parent view / app you can catch the message with the following: async def message_button_event(self, message: ButtonPressed) -> None:
# button handler |
Beta Was this translation helpful? Give feedback.
2 replies
-
|
Use the from textual.app import App, ComposeResult
from textual.widgets import Button, Static
class CounterApp(App):
def compose(self) -> ComposeResult:
yield Button("Click me!", id="my-button", variant="primary")
yield Static("Clicks: 0", id="counter")
def on_button_pressed(self, event: Button.Pressed) -> None:
"""Handle button press."""
counter = self.query_one("#counter", Static)
current = int(counter.renderable.split(": ")[1])
counter.update(f"Clicks: {current + 1}")
app = CounterApp()
app.run()For a styled button: yield Button("Submit", variant="success") # green
yield Button("Cancel", variant="error") # red
yield Button("Info", variant="primary") # blue
yield Button("Default", variant="default") # grayTo dynamically create buttons: from textual.widgets import Button
class DynamicApp(App):
def on_mount(self) -> None:
for i in range(5):
btn = Button(f"Item {i + 1}", id=f"btn-{i}")
self.mount(btn)
def on_button_pressed(self, event: Button.Pressed) -> None:
self.notify(f"Pressed: {event.button.label}")Buttons respond to click, keyboard focus (Enter/Space), and emit |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Is it possible to create a button that when pressed, triggers an event?
Beta Was this translation helpful? Give feedback.
All reactions