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

Pygame窗口调整大小后出现黑屏问题,求排查解决

问题:Pygame窗口调整大小后显示黑屏

我尝试在Pygame中调整窗口大小,但调整后仅显示黑屏。

调整前状态:700×700的灰色背景窗口,左上角有一个黄色圆形;
调整后状态:窗口尺寸改变,但整个区域变为黑屏。

原代码如下:

import pygame as pg
from pygame.locals import *

pg.init()

yellow = (255, 255, 134)
grey = (142, 142, 142)

square_size = 100
width = 7 * square_size
height = 7 * square_size
radius = int(square_size / 2 - 10)

screen = pg.display.set_mode((width, height), RESIZABLE)

screen.fill(grey)

pg.draw.circle(screen,yellow,(square_size,square_size),radius)

pg.display.flip()

while True:
    for ev in pg.event.get():
        if ev.type == pg.QUIT:
            print("quit game")
            pg.quit()
            sys.exit()
        if ev.type == pg.WINDOWRESIZED:
            width, height = screen.get_width(), screen.get_height()
    pg.display.flip()

问题原因与解决方法

  • 核心问题:窗口大小改变后,你只更新了宽高变量,但没有重新绘制任何内容。Pygame在窗口 resize 后不会保留原有画面,新的窗口区域处于未初始化状态,所以显示黑屏。
  • 次要问题:代码里用了sys.exit()但没导入sys模块,运行时会报错。

修正后的代码:

import pygame as pg
import sys
from pygame.locals import *

pg.init()

yellow = (255, 255, 134)
grey = (142, 142, 142)

square_size = 100
width = 7 * square_size
height = 7 * square_size
radius = int(square_size / 2 - 10)

screen = pg.display.set_mode((width, height), RESIZABLE)

def draw_screen():
    # 先填充背景,覆盖原有内容或新区域
    screen.fill(grey)
    # 绘制黄色圆形(如果需要适配窗口大小,可以调整坐标逻辑,这里保持原位置)
    pg.draw.circle(screen, yellow, (square_size, square_size), radius)

# 初始化绘制一次
draw_screen()
pg.display.flip()

while True:
    for ev in pg.event.get():
        if ev.type == pg.QUIT:
            print("quit game")
            pg.quit()
            sys.exit()
        if ev.type == pg.WINDOWRESIZED:
            width, height = screen.get_width(), screen.get_height()
            # 窗口调整后重新绘制所有内容
            draw_screen()
    pg.display.flip()

说明:

  1. 把绘制逻辑封装成函数,每次需要更新画面时直接调用,避免重复代码。
  2. 窗口 resize 事件触发时,调用绘制函数重新填充背景和图形,确保窗口内容正常显示。
  3. 补上了import sys,解决退出时的报错问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:41:01