How to implement screen commands? #5615
Answered
by
TomJGooding
TomJGooding
asked this question in
Q&A
-
Would anyone happen to have an example of implementing screen commands, i.e. commands that are specific to a particular screen? I'm not that familiar with command providers, but I think I understand the basics from the docs. I might be missing something obvious, but I'm struggling with how to implement this for screen commands. Many thanks in advance for any help! |
Beta Was this translation helpful? Give feedback.
Answered by
TomJGooding
Mar 5, 2025
Replies: 1 comment
-
Thanks for being my rubber duck! Turns out I had missed something obvious after all. Here's a quick example in case it helps anyone who stumbles across this: from textual.app import App, ComposeResult
from textual.command import DiscoveryHit, Hit, Hits, Provider, SimpleCommand
from textual.screen import Screen
from textual.widgets import Footer
class DeepThoughtCommands(Provider):
@property
def commands(self) -> list[SimpleCommand]:
screen = self.screen
assert isinstance(screen, DeepThoughtScreen)
commands = [
SimpleCommand(
"Calculate the answer to the Ultimate Question",
screen.ultimate_answer,
"The Ultimate Question of Life, the Universe, and Everything",
),
]
return commands
async def discover(self) -> Hits:
for name, callback, help_text in self.commands:
yield DiscoveryHit(name, callback, help=help_text)
async def search(self, query: str) -> Hits:
matcher = self.matcher(query)
for name, callback, help_text in self.commands:
score = matcher.match(name)
if score > 0:
yield Hit(
score,
matcher.highlight(name),
callback,
help=help_text,
)
class DeepThoughtScreen(Screen):
COMMANDS = {DeepThoughtCommands} | App.COMMANDS
def compose(self) -> ComposeResult:
yield Footer()
def ultimate_answer(self) -> None:
self.notify("42")
class ScreenCommandsApp(App):
def on_mount(self) -> None:
self.push_screen(DeepThoughtScreen())
if __name__ == "__main__":
app = ScreenCommandsApp()
app.run() |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
TomJGooding
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for being my rubber duck! Turns out I had missed something obvious after all.
Here's a quick example in case it helps anyone who stumbles across this: