Skip to content

animations

All animation-related classes & functions.

The biggest exports are Animation and its subclasses, as well as Animator. A global instance of Animator is also exported, under the animator name.

These can be used both within a WindowManager context (where stepping is done automatically by the pytermgui.window_manager.Compositor on every frame, or manually, by calling animator.step with an elapsed time argument.

You can register animations to the Animator using either its schedule method, with an already constructed Animation subclass, or either Animator.animate_attr or Animator.animate_float for an in-place construction of the animation instance.

animator = Animator() module-attribute

The global Animator instance used by all of the library.

Animation dataclass

The baseclass for all animations.

Source code in pytermgui/animations.py
 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
164
165
166
@dataclass
class Animation:
    """The baseclass for all animations."""

    duration: int
    direction: Direction
    loop: bool

    on_step: Callable[[Animation], bool] | None
    on_finish: Callable[[Animation], None] | None

    state: float
    _remaining: float

    def __post_init__(self) -> None:
        self.state = 0.0 if self.direction is Direction.FORWARD else 1.0
        self._remaining = self.duration
        self._is_paused = False

    def _update_state(self, elapsed: float) -> bool:
        """Updates the internal float state of the animation.

        Args:
            elapsed: The time elapsed since last update.

        Returns:
            True if the animation deems itself complete, False otherwise.
        """

        if self._is_paused:
            return False

        self._remaining -= elapsed * 1000

        self.state = (self.duration - self._remaining) / self.duration

        if self.direction is Direction.BACKWARD:
            self.state = 1 - self.state

        self.state = min(self.state, 1.0)

        if not 0.0 <= self.state < 1.0:
            if not self.loop:
                return True

            self._remaining = self.duration
            self.direction = Direction(self.direction.value * -1)

        return False

    def pause(self, setting: bool = True) -> None:
        """Pauses the animation."""

        self._is_paused = setting

    def resume(self) -> None:
        """Resumes the animation."""

        self.pause(False)

    def step(self, elapsed: float) -> bool:
        """Updates animation state.

        This should call `_update_state`, passing in the elapsed value. That call
        will update the `state` attribute, which can then be used to animate things.

        Args:
            elapsed: The time elapsed since last update.
        """

        state_finished = self._update_state(elapsed)

        step_finished = False
        if self.on_step is not None:
            step_finished = self.on_step(self)

        return state_finished or step_finished

    def finish(self) -> None:
        """Finishes and cleans up after the animation.

        Called by `Animator` after `on_step` returns True. Should call `on_finish` if it
        is not None.
        """

        if self.on_finish is not None:
            self.on_finish(self)

finish()

Finishes and cleans up after the animation.

Called by Animator after on_step returns True. Should call on_finish if it is not None.

Source code in pytermgui/animations.py
158
159
160
161
162
163
164
165
166
def finish(self) -> None:
    """Finishes and cleans up after the animation.

    Called by `Animator` after `on_step` returns True. Should call `on_finish` if it
    is not None.
    """

    if self.on_finish is not None:
        self.on_finish(self)

pause(setting=True)

Pauses the animation.

Source code in pytermgui/animations.py
130
131
132
133
def pause(self, setting: bool = True) -> None:
    """Pauses the animation."""

    self._is_paused = setting

resume()

Resumes the animation.

Source code in pytermgui/animations.py
135
136
137
138
def resume(self) -> None:
    """Resumes the animation."""

    self.pause(False)

step(elapsed)

Updates animation state.

This should call _update_state, passing in the elapsed value. That call will update the state attribute, which can then be used to animate things.

Parameters:

Name Type Description Default
elapsed float

The time elapsed since last update.

required
Source code in pytermgui/animations.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def step(self, elapsed: float) -> bool:
    """Updates animation state.

    This should call `_update_state`, passing in the elapsed value. That call
    will update the `state` attribute, which can then be used to animate things.

    Args:
        elapsed: The time elapsed since last update.
    """

    state_finished = self._update_state(elapsed)

    step_finished = False
    if self.on_step is not None:
        step_finished = self.on_step(self)

    return state_finished or step_finished

Animator

The Animator class

This class maintains a list of animations (self._animations), stepping each of them forward as long as they return False. When they return False, the animation is removed from the tracked animations.

This stepping is done when step is called.

Source code in pytermgui/animations.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
class Animator:
    """The Animator class

    This class maintains a list of animations (self._animations), stepping
    each of them forward as long as they return False. When they return
    False, the animation is removed from the tracked animations.

    This stepping is done when `step` is called.
    """

    def __init__(self) -> None:
        """Initializes an animator."""

        self._animations: list[Animation] = []

    def __contains__(self, item: object) -> bool:
        """Returns whether the item is inside _animations."""

        return item in self._animations

    @property
    def is_active(self) -> bool:
        """Determines whether there are any active animations."""

        return len(self._animations) > 0

    def step(self, elapsed: float) -> None:
        """Steps the animation forward by the given elapsed time."""

        for animation in self._animations.copy():
            if animation.step(elapsed):
                self._animations.remove(animation)
                animation.finish()

    def schedule(self, animation: Animation) -> None:
        """Starts an animation on the next step."""

        self._animations.append(animation)

    def animate_attr(self, **animation_args: Any) -> AttrAnimation:
        """Creates and schedules an AttrAnimation.

        All arguments are passed to the `AttrAnimation` constructor. `direction`, if
        given as an integer, will be converted to a `Direction` before being passed.

        Returns:
            The created animation.
        """

        if "direction" in animation_args:
            animation_args["direction"] = Direction(animation_args["direction"])

        anim = AttrAnimation(**animation_args)
        self.schedule(anim)

        return anim

    def animate_float(self, **animation_args: Any) -> FloatAnimation:
        """Creates and schedules an Animation.

        All arguments are passed to the `Animation` constructor. `direction`, if
        given as an integer, will be converted to a `Direction` before being passed.

        Returns:
            The created animation.
        """

        if "direction" in animation_args:
            animation_args["direction"] = Direction(animation_args["direction"])

        anim = FloatAnimation(**animation_args)
        self.schedule(anim)

        return anim

is_active: bool property

Determines whether there are any active animations.

__contains__(item)

Returns whether the item is inside _animations.

Source code in pytermgui/animations.py
264
265
266
267
def __contains__(self, item: object) -> bool:
    """Returns whether the item is inside _animations."""

    return item in self._animations

__init__()

Initializes an animator.

Source code in pytermgui/animations.py
259
260
261
262
def __init__(self) -> None:
    """Initializes an animator."""

    self._animations: list[Animation] = []

animate_attr(**animation_args)

Creates and schedules an AttrAnimation.

All arguments are passed to the AttrAnimation constructor. direction, if given as an integer, will be converted to a Direction before being passed.

Returns:

Type Description
AttrAnimation

The created animation.

Source code in pytermgui/animations.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
def animate_attr(self, **animation_args: Any) -> AttrAnimation:
    """Creates and schedules an AttrAnimation.

    All arguments are passed to the `AttrAnimation` constructor. `direction`, if
    given as an integer, will be converted to a `Direction` before being passed.

    Returns:
        The created animation.
    """

    if "direction" in animation_args:
        animation_args["direction"] = Direction(animation_args["direction"])

    anim = AttrAnimation(**animation_args)
    self.schedule(anim)

    return anim

animate_float(**animation_args)

Creates and schedules an Animation.

All arguments are passed to the Animation constructor. direction, if given as an integer, will be converted to a Direction before being passed.

Returns:

Type Description
FloatAnimation

The created animation.

Source code in pytermgui/animations.py
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
def animate_float(self, **animation_args: Any) -> FloatAnimation:
    """Creates and schedules an Animation.

    All arguments are passed to the `Animation` constructor. `direction`, if
    given as an integer, will be converted to a `Direction` before being passed.

    Returns:
        The created animation.
    """

    if "direction" in animation_args:
        animation_args["direction"] = Direction(animation_args["direction"])

    anim = FloatAnimation(**animation_args)
    self.schedule(anim)

    return anim

schedule(animation)

Starts an animation on the next step.

Source code in pytermgui/animations.py
283
284
285
286
def schedule(self, animation: Animation) -> None:
    """Starts an animation on the next step."""

    self._animations.append(animation)

step(elapsed)

Steps the animation forward by the given elapsed time.

Source code in pytermgui/animations.py
275
276
277
278
279
280
281
def step(self, elapsed: float) -> None:
    """Steps the animation forward by the given elapsed time."""

    for animation in self._animations.copy():
        if animation.step(elapsed):
            self._animations.remove(animation)
            animation.finish()

AttrAnimation dataclass

Bases: Animation

Animates an attribute going from one value to another.

Source code in pytermgui/animations.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
@dataclass
class AttrAnimation(Animation):
    """Animates an attribute going from one value to another."""

    target: object = None
    attr: str = ""
    value_type: type = int
    end: int | float = 0
    start: int | float | None = None

    on_step: Callable[[Animation], bool] | None = None
    on_finish: Callable[[Animation], None] | None = None

    direction: Direction = Direction.FORWARD
    loop: bool = False

    state: float = field(init=False)
    _remaining: int = field(init=False)

    def __post_init__(self) -> None:
        super().__post_init__()

        if self.start is None:
            self.start = getattr(self.target, self.attr)

        if self.end < self.start:
            self.start, self.end = self.end, self.start
            self.direction = Direction.BACKWARD

        self.end -= self.start

        _add_flag(self.target, self.attr)

    def step(self, elapsed: float) -> bool:
        """Steps forward in the attribute animation."""

        state_finished = self._update_state(elapsed)

        step_finished = False

        assert self.start is not None

        updated = self.start + (self.end * self.state)
        setattr(self.target, self.attr, self.value_type(updated))

        if self.on_step is not None:
            step_finished = self.on_step(self)

        if step_finished or state_finished:
            return True

        return False

    def finish(self) -> None:
        """Deletes `__ptg_animated__` flag, calls `on_finish`."""

        _remove_flag(self.target, self.attr)
        super().finish()

finish()

Deletes __ptg_animated__ flag, calls on_finish.

Source code in pytermgui/animations.py
242
243
244
245
246
def finish(self) -> None:
    """Deletes `__ptg_animated__` flag, calls `on_finish`."""

    _remove_flag(self.target, self.attr)
    super().finish()

step(elapsed)

Steps forward in the attribute animation.

Source code in pytermgui/animations.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
def step(self, elapsed: float) -> bool:
    """Steps forward in the attribute animation."""

    state_finished = self._update_state(elapsed)

    step_finished = False

    assert self.start is not None

    updated = self.start + (self.end * self.state)
    setattr(self.target, self.attr, self.value_type(updated))

    if self.on_step is not None:
        step_finished = self.on_step(self)

    if step_finished or state_finished:
        return True

    return False

Direction

Bases: Enum

Animation directions.

Source code in pytermgui/animations.py
73
74
75
76
77
class Direction(Enum):
    """Animation directions."""

    FORWARD = 1
    BACKWARD = -1

FloatAnimation dataclass

Bases: Animation

Transitions a floating point number from 0.0 to 1.0.

Note that this is just a wrapper over the base class, and provides no extra functionality.

Source code in pytermgui/animations.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
@dataclass
class FloatAnimation(Animation):
    """Transitions a floating point number from 0.0 to 1.0.

    Note that this is just a wrapper over the base class, and provides no extra
    functionality.
    """

    duration: int

    on_step: Callable[[Animation], bool] | None = None
    on_finish: Callable[[Animation], None] | None = None

    direction: Direction = Direction.FORWARD
    loop: bool = False

    state: float = field(init=False)
    _remaining: int = field(init=False)

is_animated(target, attribute)

Determines whether the given object.attribute is animated.

This looks for __ptg_animated__, and whether it contains the given attribute.

Source code in pytermgui/animations.py
59
60
61
62
63
64
65
66
67
68
69
70
def is_animated(target: object, attribute: str) -> bool:
    """Determines whether the given object.attribute is animated.

    This looks for `__ptg_animated__`, and whether it contains the given attribute.
    """

    if not hasattr(target, "__ptg_animated__"):
        return False

    animated = getattr(target, "__ptg_animated__")

    return attribute in animated