如何在Python中获取显示器分辨率?

201 投票
34 回答
336665 浏览
提问于 2025-04-16 00:30

获取显示器分辨率最简单的方法是什么?(最好是以元组的形式返回)

34 个回答

155

在Windows系统中,你可以使用ctypes配合GetSystemMetrics()来实现:

import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)

这样你就不需要安装pywin32这个包了;它不需要任何Python以外的东西。

如果你有多个显示器,你可以获取虚拟显示器的总宽度和高度:

import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(78), user32.GetSystemMetrics(79)
192

我创建了一个PyPI模块,就是为了这个原因:

pip install screeninfo

代码如下:

from screeninfo import get_monitors
for m in get_monitors():
    print(str(m))

结果是:

Monitor(x=3840, y=0, width=3840, height=2160, width_mm=1420, height_mm=800, name='HDMI-0', is_primary=False)
Monitor(x=0, y=0, width=3840, height=2160, width_mm=708, height_mm=399, name='DP-0', is_primary=True)

它支持多显示器环境。这个模块的目标是能够在不同的平台上使用;目前它支持Cygwin和X11,但如果有人想贡献代码,随时欢迎。

105

在Windows系统上:

from win32api import GetSystemMetrics

print("Width =", GetSystemMetrics(0))
print("Height =", GetSystemMetrics(1))

如果你在使用高分辨率的屏幕,确保你的Python解释器是HIGHDPIAWARE,也就是能够适应高分辨率显示的。

这个内容参考了这篇帖子

撰写回答