Question Details

No question body available.

Tags

python python-textual

Answers (1)

Accepted Answer Available
Accepted Answer
March 26, 2026 Score: 3 Rep: 149,400 Quality: Expert Completeness: 100%

I found two problems:

  1. Enter can be already binded to application or widget and it may not react for new binding. After taking with ChatGPT I found that it may need priority=True in Binding
Binding("enter", "select", "Select", priority=True)

Doc: Binding.priority

  1. Doesn't work self.focused == OptionList and it needs to use isinstance()
if isinstance(self.focused, OptionList):
    self.queryone(SelectionList).focus()

Full working code:

from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.widgets import OptionList, SelectionList, Footer

class ToDoApp(App): BINDINGS = [ Binding("q", "quit", "Quit", show=True), Binding("n", "new", "New ToDo", show=True), Binding("d", "delete", "Delete ToDo", show=True), Binding("j", "down", "Scroll down", show=True), Binding("k", "up", "Scroll up", show=True), # Binding("l", "select", "Select", show=True), # to check if function is working Binding("enter", "select", "Select", show=True, priority=True), ]

def compose(self) -> ComposeResult: yield OptionList("Task 1", "Task 2", "Task 3") yield SelectionList(("Done 1", 1), ("Done 2", 2)) # yield Footer()

def actionselect(self) -> None: # if self.focused == OptionList: # self.queryone(SelectionList).focus()

if isinstance(self.focused, OptionList): self.queryone(SelectionList).focus()

if name == "main": ToDoApp().run()


EDIT:

It seems better method is to use onoptionlistoptionselected to run code when enter is pressed on OptionList (without binding it)

This function gets event which has information about pressed option on OptionList - event.option -> Option('Task1'), event.optionindex -> 0

from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.widgets import OptionList, SelectionList, TextArea

class ToDoApp(App): BINDINGS = [ Binding("q", "quit", "Quit", show=True), Binding("n", "new", "New ToDo", show=True), Binding("d", "delete", "Delete ToDo", show=True), Binding("j", "down", "Scroll down", show=True), Binding("k", "up", "Scroll up", show=True), # doesn't need to bind to enter ]

def compose(self) -> ComposeResult: yield OptionList("Task 1", "Task 2", "Task 3") yield SelectionList(("Done 1", 1), ("Done 2", 2)) yield TextArea()

def onoptionlistoptionselected(self, event: OptionList.OptionSelected) -> None: """Executed when you press Enter in OptionList"""

textarea = self.queryone(TextArea) textarea.insert( f"--- selected ---\n{event.option=} | {event.optionindex=} | {event.optionid=}\n{event.optionlist.options=}\n" )

if isinstance(self.focused, OptionList): self.queryone(SelectionList).focus()

if name == "main": ToDoApp().run()

Doc: OptionList.OptionSelected

enter image description here