Monday, November 16, 2026
HomePythonTextual - An Intro to DOM Queries (Half II)

Textual – An Intro to DOM Queries (Half II)


Final month, you discovered the fundamentals of Textual’s DOM queries. If you happen to missed it, you’ll be able to learn the article now!

On this tutorial you’ll be studying in regards to the following matters:

  • The DOMQuery object
  • Getting the primary or final widget
  • Question filters
  • Question exclusions
  • Different question strategies

Let’s get began!

  • question[1]
  • len(question)
  • reverse(question)
  • and many others

Nevertheless, DOMQuery has further strategies of its very personal. You will get a listing of those strategies utilizing Python’s dir() operate towards the DOMQuery object.

To see this in motion, create a brand new file named domquery_methods.py in your Python IDE and add this code:

# domquery_methods.py
import pprint

from textual.app import App, ComposeResult
from textual.widgets import Button, Label


class QueryApp(App):

    def compose(self) -> ComposeResult:
        yield Label("Press a button", id="label")
        yield Button("Get DomQuery Strategies", id="one")

    def on_button_pressed(self) -> None:
        widgets = self.question("Button")
        s = ""
        s += f"{kind(widgets)}n"
        for entry in dir(widgets):
            s += f"{entry}n"
        label = self.query_one("#label")
        label.replace(s)


if __name__ == "__main__":
    app = QueryApp()
    app.run()

Right here, you loop over all of the entries that dir() returns and add them to your string. Then, you replace the Label as earlier than.

Once you run this code, you will note one thing like this:

Let’s spend just a few moments studying about essentially the most useful strategies from this listing!

Textual’s DOMQuery object has a few useful strategies you should utilize to get the primary or final matching widget. You’ll have observed them within the output from the earlier code instance. They’re referred to as: first() and final().

You may take the instance code from earlier with three buttons and barely replace it to ask for the primary and final widgets. For this instance, you’ll identify the file first_and_last.py and use this code:

# first_and_last.py

from textual.app import App, ComposeResult
from textual.widgets import Button, Label


class QueryApp(App):

    def compose(self) -> ComposeResult:
        yield Label("Press a button", id="label")
        yield Button("One", id="one")
        yield Button("Two", id="two")
        yield Button("Three", id="three")

    def on_button_pressed(self) -> None:
        widgets = self.question("Button")
        s = ""
        s += f"The primary button: {widgets.first()}n"
        s += f"The final button: {widgets.final()}"
        label = self.query_one("#label")
        label.replace(s)


if __name__ == "__main__":
    app = QueryApp()
    app.run()

To make every thing express, you add an id to all of the Button widgets. Then, in on_button_pressed(), you seize the primary and final widgets from the DOMQuery object and put them within the Label.

Once you run this code and press any of the buttons, you will note one thing like this:

Textual example

After all, you don’t want to make use of first() and final() in case you don’t wish to as a result of the DOMQuery object behaves like a listing. You might use widgets[0] and widgets[-1] to get the primary and final widgets if you wish to as a substitute.

Nevertheless, there are advantages to utilizing these strategies. For instance, you’ll be able to go in an expect_type argument to first() and final(), making this much more express about what kind you anticipate the primary and final widgets to be.

Right here’s an instance that expects the final widget to be a Button:

last_button = self.question().final(Button)

If the final widget is not a Button, you’ll obtain a WrongType exception.

Textual additionally supplies a filter() technique that you could be use in your DOMQuery objects. As you would possibly anticipate, the filter() is helpful for getting subsets of widgets from the question listing.

Right here is an instance the place you run a question to get all of the widgets, and then you definitely extract the Label and the Button widgets into new DOMQuery objects:

# Get all of the widgets
widgets = self.question()
# Get the Label widgets
label_widgets = widgets.filter("Label")
# Get the Button widgets
button_widgets = widgets.filter("Button")

You could exclude widgets from a DOMQuery utilizing the exclude() technique. You may consider exclude() because the logical reverse of filter(). It’s going to take away any widgets from the DOMQuery that match a CSS selector.

You should use the earlier instance to get all of the widgets. Nevertheless, this time, you wish to exclude all of the Button widgets.

Right here’s a method you can do this:

# Get all of the widgets
widgets = self.question()
# Exclude the buttons
non_buttons = widgets.exclude("Button")

With a bit of follow, you’ll be able to quickly filter and exclude as many or as few widgets as you need out of your question set.

Thus far, you will have seen get list-like DOMQuery objects that you could loop over and name every widget’s personal technique on. Nevertheless, the DOMQuery object helps a number of strategies that you could run, which can replace all of the matched widgets without having to loop over them.

A very good instance within the Textual documentation mentions you should utilize add_class() to mark widgets as “began” or “ended”. Right here’s an instance:

self.question("Enter").add_class("began")

After all, you can add every other CSS class to all of your widgets, too.

Here’s a listing of all of the strategies you should utilize that can have an effect on every thing within the question set:

  • add_class – Add a CSS class or courses.
  • blur – Removes the main focus from the widgets you matched.
  • focus – Focuses the primary matching widgets. It’s sort of the other of blur.
  • refresh – Must refresh a set of widgets? Use this technique!
  • remove_class – Removes a CSS class. In different phrases, in case you disabled your widgets with add_class(), you can re-enable them with this one.
  • take away – Take away all of the matched widgets from the DOM.
  • set_class – Units a CSS class or courses in your widget question set
  • set – Units frequent attributes in your widgets. For instance, you’ll be able to set show, seen, disabled, or loading.
  • toggle_class – Units a CSS class or courses if it’s not already set or vice-versa

You will want to spend a while making an attempt every of those out. You should use the code examples on this chapter and check out calling them towards numerous DOMQuery objects. If you happen to want a reminder of what pre-built courses can be found to you, seek advice from chapter three underneath pseudo courses or examine the Textual documentation.

Studying use DOM queries in Textual will enable you every time it’s good to do bulk updates to widgets in your software. You may be utilizing some sort of question in a lot of the purposes you construct, so understanding use them can solely enable you be more practical.

Let’s evaluate what you discovered:

  • The DOMQuery object
  • Getting the primary or final widget
  • Question filters
  • Question exclusions
  • Different question strategies

Now that you’ve got a very good grounding in working with the DOMQuery object, you must spend a while reviewing the code on this chapter and using the strategies you discovered about. Give them a attempt, and also you’ll be able to make bulk updates to your person interface very quickly!

Need to study extra about Textual? Try my guide:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments