-
Hello, I'm trying to create a TUI for my app, but I've ran into a problem. I need to return the selected option in an OptionList to a variable, but I don't know how to do it. I've read the documentation, and I did not understand it. Can someone help me? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Many widgets, where you can make some sort of selection or take some sort of action, use messages and message handlers. You'll notice that it has an As mentioned in the documentation for So, taking the first example in the documentation for from textual.app import App, ComposeResult
from textual.widgets import Footer, Header, OptionList, Label
class OptionListApp(App[None]):
CSS = """
Screen {
align: center middle;
}
OptionList {
background: $panel;
border: round $primary;
width: 70%;
height: 70%;
}
"""
def compose(self) -> ComposeResult:
yield Header()
yield OptionList(
"Aerilon",
"Aquaria",
"Canceron",
"Caprica",
"Gemenon",
"Leonis",
"Libran",
"Picon",
"Sagittaron",
"Scorpia",
"Tauron",
"Virgon",
)
yield Label("Nothing has been selected yet")
yield Footer()
def on_mount(self) -> None:
self.query_one(OptionList).focus()
def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
# Here we're showing the option that was selected.
self.query_one(Label).update(f"You selected option {event.option_index}")
# We could, of course, store the event.option_index into something
# else here. There are other useful attributes too such as:
#
# - option: the option object itself
# - option_id: The ID of the option, if it was given one.
# - option_list: A reference to the option list that sent the message.
if __name__ == "__main__":
OptionListApp().run() Give that a run and a play; hopefully that makes it clearer? |
Beta Was this translation helpful? Give feedback.
Many widgets, where you can make some sort of selection or take some sort of action, use messages and message handlers.
OptionList
is one such widget. Assuming you want to do something with the chosen item when the user pressed Enter, or similar, you want to be working with theOptionSelected
event, which in turn is a version of the generalOptionMessage
message.You'll notice that it has an
option_index
attribute. This will contain the index of the option that was selected.As mentioned in the documentation for
OptionSelected
, you'll use aon_option_list_option_selected
message handler to receive that message.So, taking the first example in the documentation for
OptionList
and building …