限制PyAutoGui的鼠标功能将起作用的区域

时间:2018-04-27 00:43:52

标签: python pyautogui

我想制作一个在油漆上随机涂鸦的程序,但是当我长时间独自涂抹它时,它会最大限度地减少油漆并移动我的每个文件 有没有办法让pyautogui不在范围外移动鼠标?提前谢谢!

import pyautogui, time, random
time.sleep(5)
pyautogui.click()    # click to put drawing program in focus
distance = random.randrange(200,300)
while 6 > 0:
    pyautogui.dragRel(distance, 0)   # move right
    distance = random.randrange(-50,50)
    pyautogui.dragRel(0, distance)   # move down
    distance = random.randrange(-50,50)
    pyautogui.dragRel(-distance, 0)  # move left
    distance = random.randrange(-50,50)
    pyautogui.dragRel(0, -distance)  # move up

我希望它保持在左上角24,163右下角1902,996

1 个答案:

答案 0 :(得分:0)

pyautogui不会为您执行此操作,但您可以跟踪x和y位置并确保其保持在范围内:

    import pyautogui, time, random

    minx = 24
    miny = 163
    maxx = 1902
    maxy = 996
    maxmove = 50
    x = (maxx-minx)/2
    y = (maxy-miny)/2
    time.sleep(5)
    pyautogui.moveTo(x, y)
    pyautogui.click()    # click to put drawing program in focus


    def inx(x):
        return x <= maxx and x >= minx


    def iny(y):
        return y <= maxy and y >= miny


    def xdrag(x):
        distx = random.randrange(maxmove) - maxmove/2
        if inx(x + distx):
            x = x + distx
            pyautogui.dragRel(distx, 0)


    def ydrag(y):
        disty = random.randrange(maxmove) - maxmove/2
        if iny(y + disty):
            y = y + disty
            pyautogui.dragRel(0, disty)


    count = 0
    while count < 100: # no infinite loop
        xdrag(x)
        ydrag(y)
        count += 1