如何解决在Python中使用ScreenInfo获取主显示器信息的问题

编程语言 2026-07-09

我有这样一个函数,它根据屏幕的宽度和高度来计算坐标,我是使用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)

然而,当我在虚拟环境之外运行它时,is_primary属性缺失,导致TypeError,程序崩溃。

if monitor.isprimary:
       ^^^^^^^^^^^^^^^^^
AttributeError: 'Monitor' object has no attribute 'isprimary'

有解决办法吗?

解决方案

Do you mean this screeninfo ?

我在源代码中找不到 isprimary。有 is_primary

也许你使用的是其他/较旧的版本,因为在版本 0.6.7 中根本就没有 is_primary。参见:源代码


还有一个方法 check_primary()

还有 get_primary_monitor() 也可以用来替代 for-循环与 get_monitors()

def formula(self, x: int, y: int) -> Tuple[int, int]:

    monitor = get_primary_monitor()

    screen_width: int = monitor.width
    screen_height: int = 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)
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章