Skip to content

checkbox

This module contains the Checkbox class.

Checkbox

Bases: Button

A simple checkbox

Source code in pytermgui/widgets/checkbox.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Checkbox(Button):
    """A simple checkbox"""

    chars = {
        **Button.chars,
        **{"delimiter": [" ", " "], "checked": "▣", "unchecked": "□"},
    }

    def __init__(
        self,
        callback: Callable[[Any], Any] | None = None,
        checked: bool = False,
        **attrs: Any,
    ) -> None:
        """Initialize object"""

        unchecked = self._get_char("unchecked")
        assert isinstance(unchecked, str)

        super().__init__(unchecked, onclick=self.toggle, **attrs)

        self.callback = None
        self.checked = False
        if self.checked != checked:
            self.toggle(run_callback=False)

        self.callback = callback

    def _run_callback(self) -> None:
        """Run the checkbox callback with the new checked flag as its argument"""

        if self.callback is not None:
            self.callback(self.checked)

    def toggle(self, *_: Any, run_callback: bool = True) -> None:
        """Toggle state"""

        chars = self._get_char("checked"), self._get_char("unchecked")
        assert isinstance(chars[0], str) and isinstance(chars[1], str)

        self.checked ^= True
        if self.checked:
            self.label = chars[0]
        else:
            self.label = chars[1]

        self.get_lines()

        if run_callback:
            self._run_callback()

__init__(callback=None, checked=False, **attrs)

Initialize object

Source code in pytermgui/widgets/checkbox.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def __init__(
    self,
    callback: Callable[[Any], Any] | None = None,
    checked: bool = False,
    **attrs: Any,
) -> None:
    """Initialize object"""

    unchecked = self._get_char("unchecked")
    assert isinstance(unchecked, str)

    super().__init__(unchecked, onclick=self.toggle, **attrs)

    self.callback = None
    self.checked = False
    if self.checked != checked:
        self.toggle(run_callback=False)

    self.callback = callback

toggle(*_, run_callback=True)

Toggle state

Source code in pytermgui/widgets/checkbox.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def toggle(self, *_: Any, run_callback: bool = True) -> None:
    """Toggle state"""

    chars = self._get_char("checked"), self._get_char("unchecked")
    assert isinstance(chars[0], str) and isinstance(chars[1], str)

    self.checked ^= True
    if self.checked:
        self.label = chars[0]
    else:
        self.label = chars[1]

    self.get_lines()

    if run_callback:
        self._run_callback()