Search code examples
pythongifkeypresskeyeventpyglet

How to display specific gif based on key press event using Pyglet?


Code I got so far

import pyglet
from pyglet.window import key
 
 

animation = pyglet.image.load_animation('/home/arctic/Downloads/work/gif/ErrorToSurprised.gif')

animSprite = pyglet.sprite.Sprite(animation)

w = animSprite.width
h = animSprite.height
 
window = pyglet.window.Window(width=w, height=h, resizable=True)
 
 
@window.event
def on_key_press(symbol, modifiers):
    if symbol == key.A:
        animation = pyglet.image.load_animation('image1.gif')
 
    elif symbol == key.B:
        animation = pyglet.image.load_animation('image2.gif')
 
    elif symbol == key.ENTER:
        print("Enter Key Was Pressed")
 
 
 
@window.event
def on_draw():
    window.clear()
 
 
 
pyglet.app.run()

This yields an error, i dont think im loading in the gif correctly under elif symbol==key. This function display a window default gif. Then listening to a key press, depending on the key display a certain gif


Solution

  • There are two problems here:

    1. You're not drawing anything to the screen in on_draw, so nothing will appear. You need to add animSprite.draw().
    2. You are correct that your method of changing the sprite animations is wrong. Currently, you are just loading an animation into a local animation variable and doing nothing with it. You have to change the animSprite.image property to a new animation.

    Here is a version of your code with both these changes.

    import pyglet
    from pyglet.window import key
    
    initial_animation = pyglet.image.load_animation(
        "/home/arctic/Downloads/work/gif/ErrorToSurprised.gif"
    )
    animation_1 = pyglet.image.load_animation("image1.gif")
    animation_2 = pyglet.image.load_animation("image2.gif")
    
    animSprite = pyglet.sprite.Sprite(initial_animation)
    
    w = animSprite.width
    h = animSprite.height
    
    window = pyglet.window.Window(width=w, height=h, resizable=True)
    
    
    @window.event
    def on_key_press(symbol, modifiers):
        if symbol == key.A:
            animSprite.image = animation_1
    
        elif symbol == key.B:
            animSprite.image = animation_2
    
        elif symbol == key.ENTER:
            print("Enter Key Was Pressed")
    
    
    @window.event
    def on_draw():
        window.clear()
        animSprite.draw()
    
    
    pyglet.app.run()