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

Pygame绘制移动万花尺时屏幕不刷新仅显示黑屏无图形问题求助

问题原因
  • Surface透明度问题:你创建的surfacetemp默认是黑色不透明背景,仅圆形位置有彩色线条,贴到主窗口时,Surface的黑色区域会覆盖已有内容,最终全黑。
  • blit参数传反:主循环中screen.blit(screen, ret)是把主屏幕本身贴到主屏幕,完全没用到你提前绘制了圆形的crect对象。
  • 位置移动逻辑错误:每次循环调用crect.get_rect()都会得到初始位置为(0,0)的矩形,你在循环内修改的偏移量不会被保存,相当于每次都从0开始计算偏移,元素无法持续移动、也不会出现在正确位置。
  • 边缘角度漏处理:alpha等于90、180、270、360/0时,没有匹配的if条件,这几个位置的圆形不会被绘制。
  • 未初始化pygame:缺少pygame.init()调用,部分pygame功能运行异常。
  • 冗余的象限判断:三角函数cos、sin本身会处理正负值,不需要手动拆分四个象限计算坐标,多余的判断反而容易出问题。
修复方案
  1. 创建Surface时开启透明通道:surfacetemp = pygame.Surface((width, height), pygame.SRCALPHA),确保只有圆形线条会被贴到主屏幕,黑色背景透掉。
  2. 修正blit参数:把存储了圆形的Surface贴到主屏幕,格式为screen.blit(圆形Surface, 目标位置)。
  3. 存储每个元素的偏移量:把Surface和对应的x偏移量绑定存储,每次循环更新偏移量,实现持续移动效果。
  4. 补全角度判断条件,或者直接删除冗余的象限判断,直接用三角函数计算坐标即可。
  5. 开头添加pygame.init()初始化pygame,每次循环先填充背景色,避免画面残留。
完整可运行代码
import pygame
import math
import sys

# 初始化pygame
pygame.init()

# 配置颜色
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255,  0)
RED = (255, 0, 0)
ORANGE = (255, 127, 0)
YELLOW = (255, 255, 0)
PURPLE = (160, 32, 240)
# 颜色顺序
listCircleColor = (RED, BLUE, GREEN, ORANGE, YELLOW, PURPLE, WHITE)
# 每组颜色的圆形数量
intGroup = 5
# 圆形之间的角度间隔
turnangle = 360/35
# 屏幕尺寸
width = 600
height = 600
# 圆形半径
radius = 100
# 创建主屏幕
screen = pygame.display.set_mode((width, height))
# 时钟控制帧率
clock = pygame.time.Clock()

circles = []
alpha = turnangle
for i in range(intGroup):
    for cl in listCircleColor:
        # 创建带透明通道的Surface
        surfacetemp = pygame.Surface((width, height), pygame.SRCALPHA)
        # 直接用三角函数计算坐标,无需拆分象限
        x = 300 + radius * math.cos(math.radians(alpha))
        y = 300 + radius * math.sin(math.radians(alpha))
        pygame.draw.circle(surfacetemp, cl, (x, y), radius, width=2)
        alpha += turnangle
        # 同时存储surface和初始x偏移量
        circles.append([surfacetemp, 0])

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    
    # 每次循环先填充黑色背景清屏
    screen.fill((0, 0, 0))
    
    for item in circles:
        surf, offset_x = item
        # 更新偏移量
        item[1] += 5
        # 把圆形Surface贴到对应位置
        screen.blit(surf, (offset_x, 0))
    
    # 刷新屏幕
    pygame.display.update()
    # 控制帧率20
    clock.tick(20)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:24:08