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

为何移动Surface会绘制线条?PyGame移动物体画线问题修复

问题:移动物体时屏幕画出线条,如何修复?

你的代码出现这个问题的核心原因:仅在程序初始化时填充了一次白色背景,后续循环里只绘制新位置的蓝色方块,旧位置的方块残留未被清除,叠加后就形成了线条。

修复方法很直接,把screen.fill((255,255,255))移到主循环内部,让每次循环都重新填充背景,覆盖掉上一帧的所有内容:

import pygame, sys, random
from pygame.locals import QUIT
pygame.init()

screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('platformer')
clock = pygame.time.Clock()

square = pygame.Surface((16,16))
square.fill((0,0,255))
square_rect = square.get_rect(center = [100, 150])

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    # 每次循环先填充背景,清除上一帧残留
    screen.fill((255,255,255))
    screen.blit(square, square_rect)
    square_rect.centerx += 5
  
    pygame.display.update()
    clock.tick(30)

修改后运行,蓝色方块会平滑移动,不会再留下拖尾线条。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 03:15:32