Skip to content

DOM Queries

In the CSS chapter we introduced the DOM which is how Textual apps keep track of widgets. We saw how you can apply styles to the DOM with CSS selectors.

Selectors are a very useful idea and can do more than apply styles. We can also find widgets in Python code with selectors, and make updates to widgets in a simple expressive way. Let's look at how!

Tip

See the Textual Query Sandbox project for an interactive way of experimenting with DOM queries.

Query one

The query_one method is used to retrieve a single widget that matches a selector or a type.

Let's say we have a widget with an ID of send and we want to get a reference to it in our app. We could do this with the following line of code:

send_button = self.query_one("#send")

This will retrieve the first widget discovered with an ID of send. If there are no matching widgets, Textual will raise a NoMatches exception.

You can also add a second parameter for the expected type, which will ensure that you get the type you are expecting.

send_button = self.query_one("#send", Button)

If the matched widget is not a button (i.e. if isinstance(widget, Button) equals False), Textual will raise a WrongType exception.

Tip

The second parameter allows type-checkers like MyPy to know the exact return type. Without it, MyPy would only know the result of query_one is a Widget (the base class).

You can also specify a widget type in place of a selector, which will return a widget of that type. For instance, the following would return a Button instance (assuming there is a single Button).

my_button = self.query_one(Button)

query_one searches the DOM below the widget it is called on, so if you call query_one on a widget, it will only find widgets that are descendants of that widget.

If you wish to search the entire DOM, you should call query_one on the App or Screen instance.

# Search the entire Screen for a widget with an ID of "send-email"
self.screen.query_one("#send-email")

Making queries

Apps and widgets also have a query method which finds (or queries) widgets. This method returns a