Key binding for switching between widgets not working #4153
Replies: 3 comments 4 replies
-
|
Widgets will register bindings when they have focus. You first need to tell Textual that a widget can receive focus by adding So if you want to focus on your backside, you can do this: class Backside(Static, can_focus=True):
... |
Beta Was this translation helpful? Give feedback.
-
|
Re visibility. If your content isn't that dynamic then it is often easier to mount them both and show/hide by setting the |
Beta Was this translation helpful? Give feedback.
-
|
Thank you very much, it works now and I'll post the full working example here below as a reference for others that want to implement switching widgets. One follow-up question, if I switch the two lines that start with def action_flip_to_backside(self) -> None:
self.parent.mount(Backside())
self.parent.query_one("Frontside").remove()Thank you very much for everything. Full working example for switching widgets: from textual import events
from textual.app import App, ComposeResult
from textual.containers import Container
from textual.widgets import Button, Static
from textual.widgets import Footer
class Frontside(Static, can_focus=True):
BINDINGS = [
("b", "flip_to_backside", "Flip to backside"),
]
def compose(self) -> ComposeResult:
yield Container(
Static("Example Frontside", classes="fronside"),
id="frontside",
)
def action_flip_to_backside(self) -> None:
self.parent.mount(Backside())
self.parent.query_one("Frontside").remove()
class Backside(Static, can_focus=True):
BINDINGS = [
("f", "flip_to_frontside", "Flip to frontside"),
]
def compose(self) -> ComposeResult:
yield Container(
Static("Example Backside", classes="backside")
)
def action_flip_to_frontside(self) -> None:
self.parent.mount(Frontside())
self.parent.query_one("Backside").remove()
class FlashcardApp(App):
BINDINGS = [
("e", "exit", "Exit"),
]
def compose(self) -> ComposeResult:
yield Frontside()
yield Footer()
def action_exit(self) -> None:
exit()
if __name__ == "__main__":
app = FlashcardApp()
app.run() |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
After working through the documentation I still couldn't figure out where the error is. In the following example, switching the widgets by pressing the buttons works, but the key binding defined in the widgets doesn't work. The expected behavior of this snippet is to be able to switch between the two widgets by pressing "b" when the Frontside widget is mounted, and by pressing "f" when the Backside widget is mounted.
The behavior that confuses me:
BTW, is it better to mount both at the same time and turn the other one invisible instead?
Beta Was this translation helpful? Give feedback.
All reactions