所以我试图在python中创建一个机器人,为此我需要屏幕的大小为两个整数(x坐标和y坐标)。我在这种情况下使用pyautogui,但函数size()只返回一个字符串:
Size(width=2560, height=1440)
我如何将这些值“提取”为整数变量?
编辑:我设法解决了我的问题,这是一些意大利面条代码,但我可以稍后清理它,以防有人遇到同样的问题:
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)
我在网上找到了多个使用pyautogui.size()的例子。在所有这些示例中,该方法返回包含宽度和高度的两项元组。因此,您的代码似乎可以像下面这样简单:
screen_size_x, screen_size_y = pyautogui.size()
print(screen_size_x)
print(screen_size_y)
这在pyautogui docs的第一个例子中显示: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)