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

Pygame display.update()未按指定Rect刷新,整行窗口被刷新求助

问题原因与解决方案

核心原因

你的问题出在macOS的Retina高DPI屏幕适配上。Pygame默认会对这类屏幕的窗口做2倍像素缩放,你传入的逻辑坐标(160,160,80,80)会被映射到物理屏幕上更大的区域,最终导致整行被错误更新。

另外,你写的pygame.display.update(((160,160,80,80)))虽然语法合法,但外层多套了一层括号(等价于直接传(160,160,80,80)),不过这不是引发异常的关键因素。

解决办法

1. 直接禁用高DPI缩放

在导入Pygame前添加环境变量设置,强制关闭高DPI适配:

import os
os.environ['SDL_VIDEO_HIGHDPI_DISABLE'] = '1'
import pygame
pygame.init()

screen = pygame.display.set_mode((400, 400))
screen.fill((255,0,0))
# 补全绘制蓝色正方形的代码(你提供的代码里漏掉了这一步)
pygame.draw.rect(screen, (0,0,255), (160,160,80,80))
pygame.display.update((160,160,80,80))

# 必须加事件循环才能保持窗口显示
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
pygame.quit()

2. 使用Rect对象明确区域

用pygame.Rect来定义更新区域,减少坐标解析的歧义:

import pygame
pygame.init()

screen = pygame.display.set_mode((400, 400))
screen.fill((255,0,0))
update_rect = pygame.Rect(160,160,80,80)
pygame.draw.rect(screen, (0,0,255), update_rect)
pygame.display.update(update_rect)

# 事件循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
pygame.quit()

3. 让Pygame自动适配缩放

创建窗口时添加pygame.SCALED标志,让Pygame自动处理高DPI的缩放逻辑:

screen = pygame.display.set_mode((400, 400), pygame.SCALED)

内容的提问来源于stack exchange,提问作者Aurélien

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:48:19