简体   繁体   English

如何使用 Pyglet 根据按键事件显示特定的 gif?

[英]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.这会产生一个错误,我认为我在 elif 符号 == 键下正确加载了 gif。 This function display a window default gif.此 function 显示 window 默认 gif。 Then listening to a key press, depending on the key display a certain gif然后听一个按键,根据按键显示一定的gif

There are two problems here:这里有两个问题:

  1. You're not drawing anything to the screen in on_draw , so nothing will appear.您没有在on_draw中在屏幕上绘制任何内容,因此不会出现任何内容。 You need to add animSprite.draw() .您需要添加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.目前,您只是将 animation 加载到本地animation变量中,并且什么都不做。 You have to change the animSprite.image property to a new animation.您必须将animSprite.image属性更改为新的 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM