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

如何在Pygame中获取屏幕分辨率,实现跨Windows/macOS全屏?

实现跨Windows/macOS的Pygame自适应全屏显示

要实现自适应系统分辨率的全屏显示,核心是通过platform模块判断系统类型,再调用对应系统的API获取屏幕分辨率,最后传入pygame.display.set_mode()。

完整实现代码

import pygame
import platform

def get_screen_resolution():
    os_type = platform.system()
    # Windows系统:调用系统API获取分辨率
    if os_type == "Windows":
        import ctypes
        user32 = ctypes.windll.user32
        return (user32.GetSystemMetrics(0), user32.GetSystemMetrics(1))
    # macOS系统:通过Quartz框架获取主屏幕分辨率
    elif os_type == "Darwin":
        import Quartz
        main_display = Quartz.CGMainDisplayID()
        display_bounds = Quartz.CGDisplayBounds(main_display)
        return (int(display_bounds.size.width), int(display_bounds.size.height))
    # 其他系统 fallback:使用Pygame内置方法
    else:
        display_info = pygame.display.Info()
        return (display_info.current_w, display_info.current_h)

# 初始化Pygame并设置自适应全屏
pygame.init()
screen_width, screen_height = get_screen_resolution()
screen = pygame.display.set_mode((screen_width, screen_height), pygame.FULLSCREEN)

# 示例主循环(按ESC退出)
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            running = False
    pygame.display.flip()

pygame.quit()

关键说明

  • Windows环境:无需额外依赖,ctypes是Python标准库,直接调用系统API获取真实分辨率。
  • macOS环境:需要先安装pyobjc(Quartz框架依赖),执行命令pip install pyobjc即可。
  • 兼容性处理:针对非Windows/macOS系统(如Linux),使用Pygame内置的display.Info()方法作为备选,保证代码通用性。
  • 退出逻辑:加入ESC键退出全屏的功能,避免测试时无法退出的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 00:12:40