Python 更改屏幕分辨率:pyautogui 与 ctypes 方法对比

本文将比较两种使用 Python 更改屏幕分辨率的方法:使用 pyautogui 库和使用 ctypes 库。

使用 pyautogui

import pyautogui

# 获取当前屏幕分辨率
screen_width, screen_height = pyautogui.size()
print('当前屏幕分辨率:{}x{}'.format(screen_width, screen_height))

# 将屏幕分辨率设置为 1920x1080
pyautogui.size(width=1920, height=1080)

# 切回之前的屏幕分辨率
pyautogui.size(width=screen_width, height=screen_height)

报错:

Traceback (most recent call last):
  File "D:\python\pycharm\lianxidaima\CQ\testing\987654321.py", line 8, in <module>
    pyautogui.size(width=1920, height=1080)
TypeError: size() got an unexpected keyword argument 'width'

原因:

pyautogui.size() 方法只能用于获取当前屏幕分辨率,无法直接设置分辨率。

使用 ctypes

import ctypes

# 获取当前屏幕分辨率
user32 = ctypes.windll.user32
screen_width = user32.GetSystemMetrics(0)
screen_height = user32.GetSystemMetrics(1)
print('当前屏幕分辨率:{}x{}'.format(screen_width, screen_height))

# 将屏幕分辨率设置为 1920x1080
user32.SetProcessDPIAware()
user32.SetProcessDPIAwareness(2)
user32.ChangeDisplaySettingsW(0, 0)

# 切回之前的屏幕分辨率
user32.ChangeDisplaySettingsW(0, 1)

解释:

  • ctypes 库允许 Python 代码直接调用 Windows API 函数。
  • user32.GetSystemMetrics() 用于获取系统信息,包括屏幕分辨率。
  • user32.SetProcessDPIAware()user32.SetProcessDPIAwareness() 用于设置 DPI 相关参数。
  • user32.ChangeDisplaySettingsW() 用于更改显示设置,其中 0 表示更改分辨率,0 表示使用系统默认模式,1 表示使用之前的模式。

结论

使用 ctypes 库可以有效地更改屏幕分辨率,而 pyautogui 库则不适合用于更改分辨率。

Python 更改屏幕分辨率:pyautogui 与 ctypes 方法对比

原文地址: https://www.cveoy.top/t/topic/qECi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录