Skip to content

Checkbox

A simple checkbox widget which stores a boolean value.

  • Focusable
  • Container

Example

The example below shows checkboxes in various states.

CheckboxApp Example checkboxes ▔▔▔▔▔▔▔▔ off:      ▁▁▁▁▁▁▁▁ ▔▔▔▔▔▔▔▔ on:       ▁▁▁▁▁▁▁▁ ▔▔▔▔▔▔▔▔ focused:  ▁▁▁▁▁▁▁▁ ▔▔▔▔▔▔▔▔ custom:   ▁▁▁▁▁▁▁▁

from textual.app import App, ComposeResult
from textual.containers import Horizontal
from textual.widgets import Checkbox, Static


class CheckboxApp(App):
    def compose(self) -> ComposeResult:
        yield Static("[b]Example checkboxes\n", classes="label")
        yield Horizontal(
            Static("off:     ", classes="label"),
            Checkbox(animate=False),
            classes="container",
        )
        yield Horizontal(
            Static("on:      ", classes="label"),
            Checkbox(value=True),
            classes="container",
        )

        focused_checkbox = Checkbox()
        focused_checkbox.focus()
        yield Horizontal(
            Static("focused: ", classes="label"), focused_checkbox, classes="container"
        )

        yield Horizontal(
            Static("custom:  ", classes="label"),
            Checkbox(id="custom-design"),
            classes="container",
        )


app = CheckboxApp(css_path="checkbox.css")
if __name__ == "__main__":
    app.run()
Screen {
    align: center middle;
}

.container {
    height: auto;
    width: auto;
}

Checkbox {
    height: auto;
    width: auto;
}

.label {
    height: 3;
    content-align: center middle;
    width: auto;
}

#custom-design {
    background: darkslategrey;
}

#custom-design > .checkbox--switch {
    color: dodgerblue;
    background: darkslateblue;
}

Reactive Attributes

Name Type Default Description
value bool False The default value of the checkbox.

Messages

Pressed

The Checkbox.Changed message is sent when the checkbox is toggled.

  • Bubbles

Attributes

attribute type purpose
value bool The new value of the checkbox.

Additional Notes

  • To remove the spacing around a checkbox, set border: none; and padding: 0;.
  • The .checkbox--switch component class can be used to change the color and background of the switch.
  • When focused, the Enter or Space keys can be used to toggle the checkbox.

See Also