在Ubuntu中使用Python获取显示器分辨率

5 投票
6 回答
14794 浏览
提问于 2025-04-16 03:28

有没有类似于win32api中GetSystemMetrics的代码,可以在Ubuntu上使用?我需要获取显示器的宽度和高度,单位是像素。

6 个回答

3
import subprocess


def get_screen_resolution():
    output = subprocess.Popen('xrandr | grep "\*" | cut -d" " -f4',shell=True, stdout=subprocess.PIPE).communicate()[0]
    resolution = output.split()[0].split(b'x')
    return {'width': resolution[0], 'height': resolution[1]}

print(get_screen_resolution())

resolution[0] 的格式是字节类型,比如 b'1020'。要把它转换成整数格式,可以试试 int(resolution[0].decode('UTF-8')) 这个方法。

8

我可以给你推荐几种可以使用的方法。不过,我没有用过xlib版本。

1) xlib(Python程序的X客户端库),如果你的系统上有的话。你可以查看“显示”方法和属性:python-xlib.sourceforge

2) 在Ubuntu系统上,你可以这样获取屏幕分辨率:

   xrandr  | grep \* | cut -d' ' -f4

3) 你可以使用subprocess这个Python模块,来运行上面的命令并提取信息。

import subprocess
output = subprocess.Popen('xrandr | grep "\*" | cut -d" " -f4',shell=True, stdout=subprocess.PIPE).communicate()[0]
print output

如果这些对你有帮助,请告诉我。

4

我猜你是在使用图形用户界面工具包。否则你为什么会关心屏幕的尺寸呢?

可以看看 gtk.gdk.screen_width()gtk.gdk.screen_height() 这两个函数,它们是PyGTK中的。QT也应该有类似的功能。

撰写回答