Skip to content

slider

This module contains the Slider class.

Slider

Bases: Widget

A Widget to display & configure scalable data.

By default, this Widget will act like a slider you might find in a settings page, allowing percentage-based selection of magnitude. Using WindowManager it can even be dragged around by the user using the mouse.

Source code in pytermgui/widgets/slider.py
 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
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
class Slider(Widget):  # pylint: disable=too-many-instance-attributes
    """A Widget to display & configure scalable data.

    By default, this Widget will act like a slider you might find in a
    settings page, allowing percentage-based selection of magnitude.
    Using `WindowManager` it can even be dragged around by the user using
    the mouse.
    """

    locked: bool
    """Disallow mouse input, hide cursor and lock current state"""

    chars = {"cursor": "", "rail": "━", "delimiter": ["[", "]"]}

    styles = w_styles.StyleManager(
        delimiter="surface",
        filled="surface+1",
        cursor="primary",
        filled_selected="primary",
        unfilled="surface-1",
        unfilled_selected="surface",
    )

    keys = {
        "increase": {keys.RIGHT, keys.CTRL_F, "l", "+"},
        "decrease": {keys.LEFT, keys.CTRL_B, "h", "-"},
    }

    def __init__(
        self,
        onchange: Callable[[float], Any] | None = None,
        locked: bool = False,
        **attrs: Any,
    ) -> None:
        """Initializes a Slider.

        Args:
            onchange: The callable called every time the value
                is updated.
            locked: Whether this Slider should accept value changes.
        """

        self._value = 0.0

        super().__init__(**attrs)
        self._selectables_length = 1

        self.is_locked = locked
        self.onchange = onchange

    @property
    def value(self) -> float:
        """Returns the value of this Slider.

        Returns:
            A floating point number between 0.0 and 1.0.
        """

        return self._value

    @value.setter
    def value(self, new: float) -> None:
        """Updates the value."""

        if self.is_locked:
            return

        self._value = max(0.0, min(new, 1.0))

        if self.onchange is not None:
            self.onchange(self._value)

    def handle_key(self, key: str) -> bool:
        """Moves the slider cursor."""

        if self.execute_binding(key):
            return True

        if key in self.keys["increase"]:
            self.value += 0.1
            return True

        if key in self.keys["decrease"]:
            self.value -= 0.1
            return True

        return False

    def handle_mouse(self, event: MouseEvent) -> bool:
        """Moves the slider cursor."""

        delimiter = self._get_char("delimiter")[0]

        if event.action in [MouseAction.LEFT_CLICK, MouseAction.LEFT_DRAG]:
            offset = event.position[0] - self.pos[0] + 1 - real_length(delimiter)
            self.value = max(0, min(offset / self.width, 1.0))
            return True

        return False

    def get_lines(self) -> list[str]:
        """Gets slider lines."""

        rail = self._get_char("rail")
        cursor = self._get_char("cursor") or rail
        delimiters = self._get_char("delimiter")

        assert isinstance(delimiters, list)
        assert isinstance(cursor, str)
        assert isinstance(rail, str)

        cursor = self._get_style("cursor")(cursor)
        unfilled = self.styles.unfilled(rail)

        if self.selected_index is None:
            filled = self.styles.filled(rail)
        else:
            filled = self.styles.filled_selected(rail)

            for i, char in enumerate(delimiters):
                delimiters[i] = self.styles.filled_selected(char)

        for i, delimiter in enumerate(delimiters):
            delimiters[i] = self.styles.delimiter(delimiter)

        width = self.width - real_length("".join(delimiters))
        count = width * self.value - 1

        chars = [delimiters[0]]

        for i in range(width):
            if i == count and not self.is_locked and self.selected_index is not None:
                chars.append(cursor)
                continue

            if i <= count:
                chars.append(filled)
                continue

            chars.append(unfilled)

        chars.append(delimiters[1])
        line = "".join(chars)
        self.width = real_length(line)

        return [line]

locked: bool class-attribute

Disallow mouse input, hide cursor and lock current state

__init__(onchange=None, locked=False, **attrs)

Initializes a Slider.

Parameters:

Name Type Description Default
onchange Callable[[float], Any] | None

The callable called every time the value is updated.

None
locked bool

Whether this Slider should accept value changes.

False
Source code in pytermgui/widgets/slider.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def __init__(
    self,
    onchange: Callable[[float], Any] | None = None,
    locked: bool = False,
    **attrs: Any,
) -> None:
    """Initializes a Slider.

    Args:
        onchange: The callable called every time the value
            is updated.
        locked: Whether this Slider should accept value changes.
    """

    self._value = 0.0

    super().__init__(**attrs)
    self._selectables_length = 1

    self.is_locked = locked
    self.onchange = onchange

get_lines()

Gets slider lines.

Source code in pytermgui/widgets/slider.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
def get_lines(self) -> list[str]:
    """Gets slider lines."""

    rail = self._get_char("rail")
    cursor = self._get_char("cursor") or rail
    delimiters = self._get_char("delimiter")

    assert isinstance(delimiters, list)
    assert isinstance(cursor, str)
    assert isinstance(rail, str)

    cursor = self._get_style("cursor")(cursor)
    unfilled = self.styles.unfilled(rail)

    if self.selected_index is None:
        filled = self.styles.filled(rail)
    else:
        filled = self.styles.filled_selected(rail)

        for i, char in enumerate(delimiters):
            delimiters[i] = self.styles.filled_selected(char)

    for i, delimiter in enumerate(delimiters):
        delimiters[i] = self.styles.delimiter(delimiter)

    width = self.width - real_length("".join(delimiters))
    count = width * self.value - 1

    chars = [delimiters[0]]

    for i in range(width):
        if i == count and not self.is_locked and self.selected_index is not None:
            chars.append(cursor)
            continue

        if i <= count:
            chars.append(filled)
            continue

        chars.append(unfilled)

    chars.append(delimiters[1])
    line = "".join(chars)
    self.width = real_length(line)

    return [line]

handle_key(key)

Moves the slider cursor.

Source code in pytermgui/widgets/slider.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def handle_key(self, key: str) -> bool:
    """Moves the slider cursor."""

    if self.execute_binding(key):
        return True

    if key in self.keys["increase"]:
        self.value += 0.1
        return True

    if key in self.keys["decrease"]:
        self.value -= 0.1
        return True

    return False

handle_mouse(event)

Moves the slider cursor.

Source code in pytermgui/widgets/slider.py
106
107
108
109
110
111
112
113
114
115
116
def handle_mouse(self, event: MouseEvent) -> bool:
    """Moves the slider cursor."""

    delimiter = self._get_char("delimiter")[0]

    if event.action in [MouseAction.LEFT_CLICK, MouseAction.LEFT_DRAG]:
        offset = event.position[0] - self.pos[0] + 1 - real_length(delimiter)
        self.value = max(0, min(offset / self.width, 1.0))
        return True

    return False

value() property writable

Returns the value of this Slider.

Returns:

Type Description
float

A floating point number between 0.0 and 1.0.

Source code in pytermgui/widgets/slider.py
68
69
70
71
72
73
74
75
76
@property
def value(self) -> float:
    """Returns the value of this Slider.

    Returns:
        A floating point number between 0.0 and 1.0.
    """

    return self._value