You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pygame动画背景卡顿:仅显示单帧无法正常播放

解决Pygame背景动画仅显示单帧的问题

问题根源

你的代码存在几个关键错误,直接导致动画无法正常播放:

  • index是animate函数的局部变量,每次调用都会重置为0,永远无法递增到下一帧
  • 每次调用animate都循环绘制所有帧,最后一帧会覆盖前面所有内容,视觉上只显示一张图
  • 帧间隔fDelay用了0.1,但pygame.time.get_ticks()返回的是毫秒,0.1会被当作0,时间判断完全失效
  • 每次绘制都重新加载图片,不仅拖慢性能,还会引发画面闪烁

修复方案

  1. 将index设为类的实例变量,保留上一次的帧索引
  2. 在类初始化时预加载所有图片到内存,避免重复IO操作
  3. 修正帧间隔单位,把0.1秒改为100毫秒
  4. 仅绘制当前索引对应的帧,取消循环绘制所有帧的逻辑

修复后的完整代码

import os
import sys
import pygame
from pygame.locals import QUIT, K_ESCAPE

basePath = os.path.dirname(sys.argv[0]) + "\\"
pygame.init()

# 设置帧率与时钟
fps = 30
fClock = pygame.time.Clock()

# 初始化窗口
res = pygame.display.Info()
tv = pygame.display.set_mode((res.current_w, res.current_h), pygame.SCALED)

class Background:
    def __init__(self):
        # 预加载所有背景帧到内存
        frame_dir = os.path.join(basePath, "Background Frames")
        self.imFrames = []
        # 可选:对文件名排序,确保播放顺序符合预期
        for filename in sorted(os.listdir(frame_dir)):
            img_path = os.path.join(frame_dir, filename)
            img = pygame.image.load(img_path).convert_alpha()
            # 将图片缩放到窗口尺寸,避免拉伸变形
            img = pygame.transform.scale(img, (res.current_w, res.current_h))
            self.imFrames.append(img)
        # 实例变量:当前帧索引、下次切换时间、帧间隔(毫秒)
        self.current_index = 0
        self.next_time = 0
        self.frame_delay = 100

    def animate(self):
        t_now = pygame.time.get_ticks()
        if t_now > self.next_time:
            self.next_time = t_now + self.frame_delay
            # 切换到下一帧,循环播放
            self.current_index += 1
            if self.current_index >= len(self.imFrames):
                self.current_index = 0
        # 绘制当前帧
        tv.blit(self.imFrames[self.current_index], (0, 0))

back = Background()
go = True
while go:
    # 事件处理
    for event in pygame.event.get():
        if event.type == QUIT:
            go = False
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                go = False

    back.animate()
    pygame.display.update()
    fClock.tick(fps)

# 退出程序
pygame.quit()
sys.exit()

额外优化提示

  • 用os.path.join()拼接路径,适配不同操作系统的路径分隔符
  • 如果需要支持窗口大小调整,可以在窗口 resize 事件中重新缩放背景帧

内容的提问来源于stack exchange,提问作者LostSilverCoin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:11:27