Python中screeninfo模块isprimary属性缺失报错的解决方法
问题
我编写了一个基于屏幕宽高计算坐标的函数,使用screeninfo模块获取屏幕信息,代码如下:
def formula(self, x: int, y: int) -> Tuple[int, int]: screen_width: int = 0 screen_height: int = 0 for monitor in get_monitors(): if monitor.isprimary: screen_width = monitor.width screen_height = monitor.height break scaling_x: int = (screen_width - 50) * (x / (self.max_x + 0.1)) + 50 scaling_y: int = (screen_height - 50) * (y / (self.max_y + 0.1)) + 50 return (scaling_x, scaling_y)
但在虚拟环境外运行时,Monitor对象缺少isprimary属性,触发如下错误导致程序崩溃:
if monitor.isprimary: ^^^^^^^^^^^^^^^^^ AttributeError: 'Monitor' object has no attribute 'isprimary'
解决方案
方法1:属性存在性检查,兼容多环境
通过hasattr()先判断Monitor对象是否包含isprimary属性,存在则用该属性筛选主屏幕;不存在则直接取列表第一个显示器(多数系统默认第一个为主屏幕):
from screeninfo import get_monitors from typing import Tuple def formula(self, x: int, y: int) -> Tuple[int, int]: screen_width: int = 0 screen_height: int = 0 monitors = get_monitors() for monitor in monitors: if hasattr(monitor, 'isprimary') and monitor.isprimary: screen_width = monitor.width screen_height = monitor.height break else: if monitors: screen_width = monitors[0].width screen_height = monitors[0].height scaling_x: int = (screen_width - 50) * (x / (self.max_x + 0.1)) + 50 scaling_y: int = (screen_height - 50) * (y / (self.max_y + 0.1)) + 50 return (scaling_x, scaling_y)
方法2:简化主屏幕获取逻辑
如果你的场景不需要严格区分主副屏幕,或者多数环境下第一个显示器就是主屏幕,可以直接取返回列表的第一个元素:
def formula(self, x: int, y: int) -> Tuple[int, int]: monitor = get_monitors()[0] screen_width = monitor.width screen_height = monitor.height scaling_x: int = (screen_width - 50) * (x / (self.max_x + 0.1)) + 50 scaling_y: int = (screen_height - 50) * (y / (self.max_y + 0.1)) + 50 return (scaling_x, scaling_y)
额外建议
screeninfo模块在不同操作系统、虚拟/非虚拟环境下的属性支持存在差异,isprimary并非全平台兼容。如果需要严格准确获取主屏幕:
- 升级screeninfo到最新版本,修复已知的跨环境兼容性问题
- 针对不同平台做底层适配:Windows用ctypes调用系统API,Linux读取X11相关配置,macOS使用Quartz框架
内容的提问来源于stack exchange,提问作者0xYNS
相关产品推荐
相关产品推荐

