pyglet.sprite

Display positioned, scaled and rotated images.

A sprite is an instance of an image displayed on-screen. Multiple sprites can display the same image at different positions on the screen. Sprites can also be scaled larger or smaller, rotated at any angle and drawn at a fractional opacity.

The following complete example loads a "ball.png" image and creates a sprite for that image. The sprite is then drawn in the window’s draw event handler:

import pyglet

ball_image = pyglet.image.load('ball.png')
ball = pyglet.sprite.Sprite(ball_image, x=50, y=50)

window = pyglet.window.Window()

@window.event
def on_draw():
    ball.draw()

pyglet.app.run()

The sprite can be moved by modifying the x and y properties. Other properties determine the sprite’s rotation, scale and opacity.

By default, sprite coordinates are restricted to integer values to avoid sub-pixel artifacts. If you require to use floats, for example for smoother animations, you can set the subpixel parameter to True when creating the sprite (:since: pyglet 1.2).

The sprite’s positioning, rotation and scaling honor its anchor_position.

Drawing multiple sprites

Sprites can be “batched” together and drawn at once more quickly than if each of their draw methods were called individually. The following example creates one hundred ball sprites and adds each of them to a Batch. The entire batch of sprites is then drawn in one call:

batch = pyglet.graphics.Batch()

ball_sprites = []
for i in range(100):
    x, y = i * 10, 50
    ball_sprites.append(pyglet.sprite.Sprite(ball_image, x, y, batch=batch))

@window.event
def on_draw():
    batch.draw()

Sprites can be freely modified in any way even after being added to a batch, however a sprite can belong to at most one batch. See the documentation for pyglet.graphics for more details on batched rendering, and grouping of sprites within batches.

Added in version 1.1.

class Sprite(
img: ImageData | Texture | Animation,
x: float = 0,
y: float = 0,
z: float = 0,
anchor: Anchor | str | tuple[float, float] | None = None,
blend_src: BlendFactor = BlendFactor.SRC_ALPHA,
blend_dest: BlendFactor = BlendFactor.ONE_MINUS_SRC_ALPHA,
batch: Batch | None = None,
group: Group | None = None,
subpixel: bool = False,
program: ShaderProgram | None = None,
) → None

Manipulate an on-screen image.

See the module documentation for usage.

Create a Sprite instance.

Parameters:
  • img (ImageData | Texture | Animation) – Image or Animation to display.

  • x (float) – X coordinate of the sprite.

  • y (float) – Y coordinate of the sprite.

  • z (float) – Z coordinate of the sprite.

  • anchor (Anchor | str | tuple[float, float] | None) – Anchor offset relative to the image’s lower-left corner. Pass a numeric (x, y) tuple for an explicit offset, or a named anchor such as "bottom_center" or TOP. Named anchors are recalculated when the image or animation frame changes.

  • blend_src (BlendFactor) – Blend source factor. The default is suitable for compositing sprites drawn from back-to-front.

  • blend_dest (BlendFactor) – Blend destination factor. The default is suitable for compositing sprites drawn from back-to-front.

  • batch (Batch | None) – Optional batch to add the sprite to.

  • group (Group | None) – Optional parent group of the sprite.

  • subpixel (bool) – Allow floating-point coordinates for the sprite. By default, coordinates are restricted to integer values.

  • program (ShaderProgram | None) – A specific shader program to initialize the sprite with. By default, a pre-made shader will be chosen based on the texture type passed. Sprite colors are uploaded as four unsigned bytes; custom programs must use vertex_layout=pyglet.graphics.VertexLayout(colors="4Bn") so the values are normalized for the shader.

Changed in version 2.0.16: Added program parameter.

Changed in version 3.0: Added anchor parameter.

group_class

Default class used to create the rendering group.

alias of SpriteGroup

delete() → None

Force immediate removal of the sprite from video memory.

It is recommended to call this whenever you delete a sprite, as the Python garbage collector will not necessarily call the finalizer as soon as the sprite falls out of scope.

Return type:

None

draw() → None

Draw the sprite at its current position.

See the module documentation for hints on drawing multiple sprites efficiently.

Return type:

None

get_sprite_group() → SpriteGroup | Group

Creates and returns a group to be used to render the sprite.

This is used internally to create a consolidated group for rendering.

Note

This is for advanced usage. This is a group automatically created internally as a child of group, and does not need to be modified unless the parameters of your custom group changes.

Added in version 2.0.16.

Return type:

SpriteGroup | Group

on_animation_end() → None | Literal[True]

The sprite animation reached the final frame.

The event is triggered only if the sprite has an animation, not an image. For looping animations, the event is triggered each time the animation loops.

Event:

Return type:

None | Literal[True]

update(
x: float | None = None,
y: float | None = None,
z: float | None = None,
rotation: float | None = None,
scale: float | None = None,
scale_x: float | None = None,
scale_y: float | None = None,
) → None

Simultaneously change the position, rotation or scale.

This method is provided for convenience. There is not much performance benefit to updating multiple Sprite attributes at once.

Parameters:
  • x (float | None) – X coordinate of the sprite.

  • y (float | None) – Y coordinate of the sprite.

  • z (float | None) – Z coordinate of the sprite.

  • rotation (float | None) – Clockwise rotation of the sprite, in degrees.

  • scale (float | None) – Scaling factor.

  • scale_x (float | None) – Horizontal scaling factor.

  • scale_y (float | None) – Vertical scaling factor.

Return type:

None

Deprecated since version 2.0.x: No longer calculated with the vertices on the CPU. Now calculated within a shader.

  • Use x, y, z, or position to update position.

  • Use rotation to update rotation.

  • Use scale_x, scale_y, or scale to update scale.

property anchor: Anchor | None

The named anchor position, or None when using a numeric anchor.

property anchor_position: tuple[float, float]

The anchor’s (x, y) offset from the sprite’s lower-left corner.

property anchor_x: float

X coordinate of the anchor, relative to the image’s left edge.

property anchor_y: float

Y coordinate of the anchor, relative to the image’s bottom edge.

property batch: Batch | None

Graphics batch.

The sprite can be migrated from one batch to another, or removed from its batch (for individual drawing).

Note

Changing this can be an expensive operation as it involves deleting the vertex list and recreating it.

property blend_mode: tuple[BlendFactor, BlendFactor]

The current blend mode applied to this sprite.

Note

Changing this can be an expensive operation as it involves a group creation and transfer.

property color: tuple[int, int, int, int]

Blend color.

This property sets the color of the sprite’s vertices. This allows the sprite to be drawn with a color tint.

The color is specified as either an RGBA tuple of integers ‘(red, green, blue, opacity)’ or an RGB tuple of integers (red, blue, green).

If there are fewer than three components, a :py:func`ValueError` will be raised. Each color component must be an int in the range 0 (dark) to 255 (saturated). If any component is not an int, a TypeError will be raised.

event_types: list = ['on_animation_end']
property frame_index: int

The current Animation frame.

If the Sprite.image is an Animation, you can query or set the current frame. If not an Animation, this will always be 0.

property group: Group | None

Parent graphics group specified by the user.

This group will always be the parent of the internal sprite group.

Note

Changing this can be an expensive operation as it involves a group creation and transfer.

property height: float

Scaled height of the sprite.

Invariant under rotation.

property image: Texture | Animation

The Sprite’s Image or Animation to display.

Note

Changing this can be an expensive operation if the texture is not part of the same texture or atlas.

property opacity: int

Blend opacity.

This property sets the alpha component of the colour of the sprite’s vertices. With the default blend mode (see the constructor), this allows the sprite to be drawn with fractional opacity, blending with the background.

An opacity of 255 (the default) has no effect. An opacity of 128 will make the sprite appear translucent.

property paused: bool

Pause/resume the Sprite’s Animation.

If Sprite.image is an Animation, you can pause or resume the animation by setting this property to True or False. If not an Animation, this has no effect.

property position: tuple[float, float, float]

The (x, y, z) coordinates of the sprite, as a tuple.

property program: ShaderProgram

The current shader program.

Note

Changing this can be an expensive operation as it involves a group creation and transfer.

property rotation: float

Clockwise rotation of the sprite, in degrees.

The sprite is rotated about its anchor_position.

property scale: float

Base Scaling factor.

A scaling factor of 1.0 (the default) has no effect. A scale of 2.0 will draw the sprite at twice the native size of its image.

property scale_x: float

Horizontal scaling factor.

A scaling factor of 1.0 (the default) has no effect. A scale of 2.0 will draw the sprite at twice the native width of its image.

property scale_y: float

Vertical scaling factor.

A scaling factor of 1.0 (the default) has no effect. A scale of 2.0 will draw the sprite at twice the native height of its image.

property visible: bool

True if the sprite will be drawn.

property width: float

Scaled width of the sprite.

Invariant under rotation.

property x: float

X coordinate of the sprite.

property y: float

Y coordinate of the sprite.

property z: float

Z coordinate of the sprite.

class SpriteGroup(
texture: Texture,
blend_src: BlendFactor,
blend_dest: BlendFactor,
program: ShaderProgram,
parent: Group | None = None,
) → None

Shared Sprite rendering Group.

Create a sprite group.

The group is created internally when a Sprite is created; applications usually do not need to explicitly create it.

Parameters:
  • texture (Texture) – The (top-level) texture containing the sprite image.

  • blend_src (BlendFactor) – Blend factor source mode; for example: SRC_ALPHA.

  • blend_dest (BlendFactor) – Blend factor source mode; for example: _ONE_MINUS_SRC_ALPHA.

  • program (ShaderProgram) – A custom ShaderProgram.

  • parent (Group | None) – Optional parent group.

class MultiTextureSprite(
images: dict[str, ImageData | Texture | Animation],
x: float = 0,
y: float = 0,
z: float = 0,
anchor: Anchor | str | tuple[float, float] | None = None,
blend_src: BlendFactor = BlendFactor.SRC_ALPHA,
blend_dest: BlendFactor = BlendFactor.ONE_MINUS_SRC_ALPHA,
batch: Batch | None = None,
group: Group | None = None,
subpixel: bool = False,
program: ShaderProgram | None = None,
) → None

Sprite variant that renders and animates multiple texture layers.

Create a MultiTextureSprite instance.

Parameters:
  • images (dict[str, ImageData | Texture | Animation]) – Dictionary of named Image, Texture, or Animation layers to display. Keys are used as sampler names in the shader.

  • x (float) – X coordinate of the sprite.

  • y (float) – Y coordinate of the sprite.

  • z (float) – Z coordinate of the sprite.

  • anchor (Anchor | str | tuple[float, float] | None) – Anchor offset relative to the largest layer’s lower-left corner. Pass a numeric (x, y) tuple for an explicit offset, or a named anchor that is recalculated when the anchor texture changes.

  • blend_src (BlendFactor) – Blend source factor. The default is suitable for compositing sprites drawn from back-to-front.

  • blend_dest (BlendFactor) – Blend destination factor. The default is suitable for compositing sprites drawn from back-to-front.

  • batch (Batch | None) – Optional batch to add the sprite to.

  • group (Group | None) – Optional parent group of the sprite.

  • subpixel (bool) – Allow floating-point coordinates for the sprite. By default, coordinates are restricted to integer values.

  • program (ShaderProgram | None) – A specific shader program to initialize the sprite with. By default, a generated multi-texture shader will be chosen based on the layer types passed.

Added in version 3.0.

group_class

alias of MultiTextureSpriteGroup

delete() → None

Force immediate removal of the sprite from video memory.

It is recommended to call this whenever you delete a sprite, as the Python garbage collector will not necessarily call the finalizer as soon as the sprite falls out of scope.

Return type:

None

get_frame_index(name: str) → int

Get the current animation frame for a single layer.

Return type:

int

get_layer(
name: str,
) → ImageData | Texture | Animation | None

Return the source image or animation for a layer.

Return type:

ImageData | Texture | Animation | None

get_sprite_group() → MultiTextureSpriteGroup

Creates and returns a group to be used to render the sprite.

This is used internally to create a consolidated group for rendering.

Note

This is for advanced usage. This is a group automatically created internally as a child of group, and does not need to be modified unless the parameters of your custom group changes.

Added in version 2.0.16.

Return type:

MultiTextureSpriteGroup

set_frame_index(name: str, frame_idx: int) → None

Set the current animation frame for a single layer.

Return type:

None

set_layer(
name: str,
img: ImageData | Texture | Animation,
) → None

Replace an existing layer image or animation.

Return type:

None

property frame_index: NoReturn

The current Animation frame.

If the Sprite.image is an Animation, you can query or set the current frame. If not an Animation, this will always be 0.

property image: NoReturn

The Sprite’s Image or Animation to display.

Note

Changing this can be an expensive operation if the texture is not part of the same texture or atlas.

property paused: bool

Pause/resume the Sprite’s Animation.

If Sprite.image is an Animation, you can pause or resume the animation by setting this property to True or False. If not an Animation, this has no effect.

class MultiTextureSpriteGroup(
textures: dict[str, Texture],
blend_src: BlendFactor,
blend_dest: BlendFactor,
program: ShaderProgram,
parent: Group | None = None,
) → None

Shared Multi-texture Sprite rendering Group.

Create a sprite group that binds multiple textures and sampler uniforms.