pyautogui使用size()获得两个整数

时间:2019-03-22 16:48:15

标签: python pyautogui

所以我试图用python创建一个机器人,因此,我需要屏幕的大小为两个整数(x坐标和y坐标)。在这种情况下,我使用pyautogui,但是函数size()仅返回一个字符串:

Size(width=2560, height=1440)

我该如何将这些值“提取”为整数变量?

编辑:我设法解决了我的问题,这是一些spagetthi代码,但我可以稍后进行清理,以防万一有人遇到相同的问题:

import pyautogui


screen_size = str(pyautogui.size())
screen_size_x, screen_size_y = screen_size.split(",")
screen_size_x= screen_size_x.replace("Size(width=","")
screen_size_y = screen_size_y.replace("height=","")
screen_size_y = screen_size_y.replace(")","")
screen_size_y = screen_size_y.replace(" ","")
screen_size_x = int(screen_size_x)
screen_size_y = int(screen_size_y)
print(screen_size_x)
print(screen_size_y)

2 个答案:

答案 0 :(得分:1)

from inspect import getsource
print(getsource(pyautogui.size))

输出:

def size():
    """Returns the width and height of the screen as a two-integer tuple.

    Returns:
      (width, height) tuple of the screen size, in pixels.
    """
    return Size(*platformModule._size())

nicer代码:

import pyautogui

x,y = pyautogui.size()
x,y=int(str(x)),int(str(y))
print(x)
print(y)

答案 1 :(得分:0)

我在网上发现了多个使用pyautogui.size()的示例。在所有这些示例中,该方法返回包含宽度和高度的两个项目元组。因此,您的代码似乎很简单:

screen_size_x, screen_size_y = pyautogui.size()
print(screen_size_x)
print(screen_size_y)

这在pyautogui文档的第一个示例中显示:https://github.com/asweigart/pyautogui/blob/master/README.md

如果您确实需要解析您提到的字符串,这是一种更简洁的方法:

import re
str = "Size(width=2560, height=1440)"
m = re.search(r"width=(\d+).*height=(\d+)", str)
screen_size_x, screen_size_y = int(m.group(1)), int(m.group(2))
print(screen_size_x)
print(screen_size_y)