Pygame窗口弹出后最小化且无响应问题求助
Pygame窗口弹出后最小化且未响应的解决方案
代码层面修复
你的脚本存在一个性能问题:每次循环都创建新的pygame.time.Clock对象,导致帧率控制失效,进而引发窗口卡顿甚至未响应。修改如下:
import pygame import sys # Initialize Pygame pygame.init() # Set up the display width, height = 800, 600 screen = pygame.display.set_mode((width, height)) pygame.display.set_caption("Simple Pygame Example") # Define colors white = (255, 255, 255) blue = (0, 0, 255) # Set up the rectangle rect_x, rect_y = width // 2, height // 2 rect_width, rect_height = 50, 50 rect_speed = 5 # 初始化Clock对象,放在循环外 clock = pygame.time.Clock() # Main loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Get pressed keys keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: rect_x -= rect_speed if keys[pygame.K_RIGHT]: rect_x += rect_speed if keys[pygame.K_UP]: rect_y -= rect_speed if keys[pygame.K_DOWN]: rect_y += rect_speed # Fill the screen with white screen.fill(white) # Draw the rectangle pygame.draw.rect(screen, blue, (rect_x, rect_y, rect_width, rect_height)) # Update the display pygame.display.flip() # 用同一个Clock对象控制帧率 clock.tick(60)
环境层面排查(若代码修改后仍未解决)
如果修改代码后问题依旧,尝试以下步骤:
- 卸载并重装Pygame:执行
pip uninstall pygame -y && pip install pygame,或指定稳定版本pip install pygame==2.5.2 - 切换到软件渲染模式:创建窗口时添加
pygame.SOFTWARE参数禁用硬件加速:screen = pygame.display.set_mode((width, height), pygame.SOFTWARE) - 更新显卡驱动:前往显卡厂商官网(NVIDIA/AMD/Intel)下载安装最新驱动
- 使用虚拟环境隔离依赖:创建独立Python环境重新安装Pygame:
# 创建虚拟环境 python -m venv pygame_env # Windows激活环境 pygame_env\Scripts\activate # Linux/macOS激活环境 source pygame_env/bin/activate # 安装Pygame pip install pygame - 关闭冲突软件:暂停屏幕录制、虚拟桌面、杀毒软件等可能拦截窗口或占用显示资源的程序
内容的提问来源于stack exchange,提问作者Gabe
相关产品推荐
相关产品推荐

