PAYATHON 2026

Python 使用 screeninfo 获取主显示器信息时出现 AttributeError,如何解决?

数据小陈

先将 monitor.isprimary 改为 monitor.is_primary。screeninfo 的 Monitor 定义使用带下划线的 is_primary,该字段允许为 None。原报错 AttributeError 表示访问了对象不存在的属性。screeninfo 的 Monitor 定义

虚拟环境内外行为不同,还需要检查实际使用的解释器和 screeninfo 安装位置。仅凭这段报错,无法确定两边是否存在版本差异。

先修正属性名

原代码中的:

if monitor.isprimary:

应改为:

if monitor.is_primary:

修改后,还要处理没有识别到主显示器的情况。原代码将宽高初始化为 0,如果循环没有找到主屏,后续公式仍会继续计算,得到没有意义的结果。

给主屏查找添加明确的失败处理

下面的代码保留原来的坐标计算公式,并在没有显示器或没有主屏标记时抛出异常:

from typing import Tuple
from screeninfo import get_monitors


def formula(self, x: int, y: int) -> Tuple[float, float]:
    monitors = get_monitors()
    if not monitors:
        raise RuntimeError("screeninfo 未返回任何显示器")

    primary = next(
        (
            monitor
            for monitor in monitors
            if getattr(monitor, "is_primary", None) is True
        ),
        None,
    )
    if primary is None:
        raise RuntimeError("无法确定主显示器,请检查显示器信息和运行环境")

    screen_width = primary.width
    screen_height = primary.height

    scaling_x = (screen_width - 50) * (x / (self.max_x + 0.1)) + 50
    scaling_y = (screen_height - 50) * (y / (self.max_y + 0.1)) + 50
    return scaling_x, scaling_y

这里的 getattr() 用于处理属性缺失,不会替缺少的主屏信息作判断。is_primary 不存在或为 None 的显示器不会被选为主屏;如果找不到 is_primary 为 True 的显示器,代码会明确失败。

原公式中的 / 会产生浮点结果,因此示例将返回类型改为 Tuple[float, float]。如果调用方要求整数坐标,可以明确采用四舍五入:

return round(scaling_x), round(scaling_y)

此时再将返回类型标注为 Tuple[int, int]。

对比虚拟环境内外的实际安装

分别在虚拟环境内外运行以下诊断代码:

import sys
import screeninfo
from importlib.metadata import version
from screeninfo import get_monitors

print("Python:", sys.executable)
print("screeninfo path:", screeninfo.__file__)
print("screeninfo version:", version("screeninfo"))

for monitor in get_monitors():
    print(monitor)
    print("has isprimary:", hasattr(monitor, "isprimary"))
    print("has is_primary:", hasattr(monitor, "is_primary"))
    print("is_primary:", getattr(monitor, "is_primary", None))

比较解释器路径、包版本、模块路径,以及各显示器的实际属性。如果模块路径指向项目中的同名 screeninfo.py 或 screeninfo 目录,应先排除导入了错误模块的情况。

安装或检查依赖时,使用运行程序的同一个 Python 解释器。例如:

python -m pip show screeninfo

这里的 python 必须对应目标解释器,必要时使用其完整路径。若确认两个环境的版本不同,再将目标环境的 screeninfo 对齐到已验证可用的版本。不要仅根据“虚拟环境外出错”就认定需要升级。

没有主屏标记时如何处理

先检查枚举结果,确认是否存在 is_primary=True 的显示器。只有业务允许使用任意显示器时,才考虑回退到第一项;get_monitors()[0] 不能作为主显示器身份的依据。

当前公式计算的是相对于所选显示器的坐标。如果调用方要求多显示器桌面的全局坐标,还需在坐标单位一致的前提下,结合该显示器的 x、y 偏移进行转换。

备注:内容仅供参考。