-
I have a situation where I want the action taken from a button press to be an actual keypress to trigger the appropriate binding. Currently I'm using the internal App._press_keys() method which is working fine, but I know this isn't intended for public use. Is there a better way do to this? async def simulate_key(self, key: str) -> None:
"""Simulate a keypress"""
await self._press_keys(key) My working use case is a reused generic modal confirmation dialog - the dialog message and bindings for for "Y" and "N" responses are set each time before the dialog is displayed. I have the Button Widget presses simply simulate the "Y" and "N" responses to trigger the appropriate bindings rather than adding more logic to also customize the on_button_pressed logic. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
To the best of my knowledge, there isn't an exposed method of simulating a key press. If I'm understanding correctly what you want to do (a yes/no dialog that has yes/no buttons but also handles Y/N key press), I think I'd start with something like this: from textual.app import App, ComposeResult
from textual.widgets import Static, Button
from textual.containers import Horizontal
class Discussion1129( App[ str ] ):
CSS = """
#question {
border: solid green;
}
Button {
margin: 2;
}
"""
BINDINGS = [
( "y", "result( 'y' )", "" ),
( "n", "result( 'n' )", "" )
]
def compose( self ) -> ComposeResult:
yield Static( "A strange game. The only winning move is not to play. How about a nice game of chess?", id="question" )
yield Horizontal(
Button( "Yes please", id="y" ),
Button( "No thanks", id="n" )
)
def on_button_pressed( self, event: Button.Pressed ) -> None:
self.action_result( event.button.id )
def action_result( self, answer: str ):
self.exit( answer )
if __name__ == "__main__":
print( Discussion1129().run() ) |
Beta Was this translation helpful? Give feedback.
To the best of my knowledge, there isn't an exposed method of simulating a key press. If I'm understanding correctly what you want to do (a yes/no dialog that has yes/no buttons but also handles Y/N key press), I think I'd start with something like this: