Example #1
3
def temp():
    pyautogui.alert('This displays some text with an OK button.')
    pyautogui.position()  # current mouse x and y
    pyautogui.onScreen(x, y)  # True if x & y are within the screen.
    pyautogui.PAUSE = 2.5   # Pause 2.5 s
    pyautogui.dragTo(x, y, duration=num_seconds)  # drag mouse to XY
    pyautogui.dragRel(xOffset, yOffset, duration=num_seconds)  # drag mouse relative to its current position
    pyautogui.click(x=moveToX, y=moveToY, clicks=num_of_clicks, interval=secs_between_clicks, button='left') # The button keyword argument can be 'left', 'middle', or 'right'.
    pyautogui.scroll(amount_to_scroll, x=moveToX, y=moveToY)
    pyautogui.mouseDown(x=moveToX, y=moveToY, button='left')
    pyautogui.mouseUp(x=moveToX, y=moveToY, button='left')
    pyautogui.typewrite('Hello world!\n', interval=secs_between_keys)  # useful for entering text, newline is Enter
    pyautogui.typewrite(['a', 'b', 'c', 'left', 'backspace', 'enter', 'f1'], interval=secs_between_keys)
    pyautogui.hotkey('ctrl', 'c')  # ctrl-c to copy
    pyautogui.hotkey('ctrl', 'v')  # ctrl-v to paste
    pyautogui.alert('This displays some text with an OK button.')
    pyautogui.confirm('This displays text and has an OK and Cancel button.')
    pyautogui.prompt('This lets the user type in a string and press OK.')
    pyautogui.screenshot('foo.png')  # returns a Pillow/PIL Image object, and saves it to a file
    pyautogui.locateOnScreen('looksLikeThis.png')
    pyautogui.locateCenterOnScreen('looksLikeThis.png')  # returns center x and y
Example #2
0
def pyautogui_move_demo():
    x, y = pyautogui.size()

    print('屏幕分辨率为:%d,%d' % (int(x), int(y)))
    # 该模块默认屏幕的原点在左上角,位置为(0, 0)
    # px, py = pyautogui.position()
    # print('当前鼠标的位置为:%d,%d' % (px, py))
    # 判断某个位置是否在屏幕上
    print('(-1, 100)的点判断结果:', pyautogui.onScreen(-1, 100))
    print('(1000, 100)的点判断结果:', pyautogui.onScreen(1000, 100))
    # 延迟几秒之后执行,全部的pyautogui都将延迟之后执行
    # pyautogui.PAUSE = 5
    # 移动鼠标
    pyautogui.moveTo(x/2, y/2)
    # 带有延迟的鼠标移动
    pyautogui.moveTo(100, 200, 2)
    # 带有延迟的鼠标移动,且移动速度带有变化,None表示当前该坐标不变
    pyautogui.moveTo(1000, None, 2, pyautogui.easeInQuad)  # 开始慢,越来越快
    print_position()
    # 相对位置的移动鼠标
    pyautogui.move(50, 100)
    pyautogui.move(-50, 100)
    # None表示当前该坐标不变
    pyautogui.move(None, 100)
    print_position()

    '''# 画图  需要打开画图板软件
Example #3
0
def test():
    # 判断(x,y)是否在屏幕上
    x, y = 122, 244
    pyautogui.onScreen(x, y)  # 结果为true

    width, height = pyautogui.size()  # 屏幕的宽度和高度
    print(width, height)
Example #4
0
def screen():
    """
    原点(0,0)在左上角,分别向右、向下增大
    如果屏幕像素是 1920×10801920×1080 ,那么右下角的坐标是(1919, 1079)
    :return: 
    """
    # 当前屏幕的分辨率(宽度和高度)
    screenWidth, screenHeight = pyautogui.size()

    # 鼠标当前位置
    currentMouseX, currentMouseY = pyautogui.position()
    #  (x,y)是否在屏幕上
    x, y = 122, 244
    pyautogui.onScreen(x, y)
    def move(self, x, y):
        mx, my = pyautogui.position()
        x_distance = x * self.precision
        y_distance = -1 * y * self.precision

        if pyautogui.onScreen(mx + x_distance, my + y_distance):
            pyautogui.moveRel(x_distance, y_distance, duration=self.speed)
Example #6
0
def check_on_screen():
    x, y = pag.position()
    if not pag.onScreen(x, y):
        pag.alert("Your mouse is not on the screen, you probaply have 2 Screens, This program can only accsess your "
                  "main screen, you can change your main screen in the Windows settings")
        return False
    return True
def move_cursor(cur_x, cur_y, is_fast):
    global prev_x, prev_y, mouse_speed, movement_thrashold, prev_time, time_thrashold
    cur_time = time.time()
    # If mouse is just selected
    if prev_x == -1 or (cur_time - prev_time) > time_thrashold:
        prev_x, prev_y = cur_x, cur_y
        prev_time = cur_time
        return

    # Ignore very slight movements
    if abs(cur_x-prev_x) + abs(cur_y-prev_y) < movement_thrashold:
        return

    # Move mouse
    x_move = (cur_x - prev_x) * mouse_speed
    y_move = (cur_y - prev_y) * mouse_speed
    dur = 1
    if is_fast:
        x_move = x_move * fast_speed
        y_move = y_move * fast_speed
        dur = 0
    cursor_x, cursor_y = pyautogui.position()
    if pyautogui.onScreen(cursor_x+x_move, cursor_y+y_move):
        
        pyautogui.moveRel(x_move, y_move, duration=0.0001 * dur)
        # pyautogui.moveTo(cursor_x+x_move, cursor_y+y_move, duration = time_dif/100)

    prev_x, prev_y = cur_x, cur_y
Example #8
0
 def ispicture(self, el):
     '''判断图片是否存在'''
     picPath = os.path.join(rootPath, config['pic']['contrastPath'], el)
     x, y = pyautogui.locateCenterOnScreen(picPath, minSearchTime=self.minSearchTime)
     isnot = pyautogui.onScreen(x, y)
     if isnot == True:
         return True
     else:
         return False
Example #9
0
def draw_modified(step, centerX, centerY, radius, numSpokes):
    colorX = [805, 831, 854, 872, 894, 920, 942, 959]
    colorY = [59, 81]
    colXIdx, colYIdx = pickRandomColor()
    oldCenterX = centerX
    oldCenterY = centerY
    if centerY < 170:
        centerY = 990 - (centerY + 170)
        oldCenterY = 988
    if centerY > 990:
        centerY = 170 + (centerY - 990)
        oldCenterY = 172
    if centerX < 10:
        centerX = 1070 - (centerX + 10)
        oldCenterX = 1068
    if centerX > 1070:
        centerX = 10 + (centerX - 1070)
        oldCenterX = 12
    if pyautogui.onScreen(oldCenterX, oldCenterY) and pyautogui.onScreen(
            centerX, centerY):
        pyautogui.moveTo(oldCenterX, oldCenterY)
        pyautogui.dragTo(centerX, centerY)
    else:
        centerX, centerY = moveToCenter()
    points = PointsInCircum(radius, numSpokes)
    numPoints = len(points)
    flipFlag = random.randrange(0, 100, 1)
    if flipFlag > 50:
        points.reverse()
    startIdx = random.randrange(0, numPoints - 1, 1)
    endIdx = random.randrange(startIdx, numPoints - 1, 1)
    if startIdx >= endIdx:
        startIdx = 0
    for idx in range(startIdx, endIdx):
        x, y = points[idx]
        pyautogui.dragRel(x, y)
        if step > 0:
            newStep = step - 1
            newRadius = radius / 2
            newCenterX, newCenterY = pyautogui.position()
            drawModified(newStep, newCenterX, newCenterY, newRadius, numSpokes)
        pyautogui.click(x=colorX[colXIdx], y=colorY[colYIdx])
        pyautogui.moveTo(centerX, centerY)
    def unpack(self, event):
        super().unpack(event)
        try:
            event["event_key"] = eval(event["event_key"])
        except NameError:
            event["event_key"] = event["event_key"]
        assert isinstance(event["event_key"], Button)

        assert pyautogui.onScreen(event["position_x"], event["position_y"])
        return event
Example #11
0
def mouse_move(data):
    if 'xy' in data:
        x, y = data['xy']
        if pyautogui.onScreen(x, y):
            pyautogui.moveTo(*data['xy'])
        else:
            size = pyautogui.size()
            data['error'] = f"Эти координаты ({x}; {y}) " \
                f"находятся вне вашего экрана ({size.width}; {size.height})"
    else:
        data['error'] = "Требуется аргумент 'xy'"
    return data
Example #12
0
    def move(self, x, y):

        # if(abs( x - self.prevx) < 0.09 and abs( y - self.prevy) < 0.09):
        #     print(abs( x - self.prevx))
        #     self.prevx = x
        #     self.prevy = y

        #     return

        mx, my = pyautogui.position()
        xdistance = x * self.precision  #if  x*self.precision > 5 else 0
        ydistance = -1 * y * self.precision  #if -1*y*self.precision > 5 else 0

        if (pyautogui.onScreen(mx + xdistance, my + ydistance)):
            pyautogui.moveRel(xdistance, ydistance, duration=self.speed)
Example #13
0
    def test_onScreen(self):
        zero = P(0, 0)
        xone = P(1, 0)
        yone = P(0, 1)
        size = P(*pyautogui.size())
        half = size / 2

        on_screen = [
            zero, zero + xone, zero + yone, zero + xone + yone, half,
            size - xone - yone
        ]
        off_screen = [
            zero - xone, zero - yone, zero - xone - yone, size - xone,
            size - yone, size
        ]

        for value, coords in [(True, on_screen), (False, off_screen)]:
            for coord in coords:
                self.assertEqual(
                    value,
                    pyautogui.onScreen(*coord),
                    "onScreen({0}, {1}) should be {2}".format(
                        coord.x, coord.y, value),
                )
                self.assertEqual(
                    value,
                    pyautogui.onScreen(list(coord)),
                    "onScreen([{0}, {1}]) should be {2}".format(
                        coord.x, coord.y, value),
                )
                self.assertEqual(
                    value,
                    pyautogui.onScreen(tuple(coord)),
                    "onScreen(({0}, {1})) should be {2}".format(
                        coord.x, coord.y, value),
                )
                self.assertEqual(
                    value, pyautogui.onScreen(coord),
                    "onScreen({0}) should be {1}".format(repr(coord), value))

        # These raise PyAutoGUIException.
        with self.assertRaises(pyautogui.PyAutoGUIException):
            pyautogui.onScreen([0, 0], 0)
        with self.assertRaises(pyautogui.PyAutoGUIException):
            pyautogui.onScreen((0, 0), 0)
Example #14
0
    def move(self, x, y):
        current_pos = pyautogui.position()  # current mouse position on screen
        rel_x = x * self.precision  # relative movement on x axis
        rel_y = -1 * y * self.precision  # relative movement on y axis
        new_pos = (current_pos[0] + rel_x, current_pos[1] + rel_y)  # new potential position

        # If the new position is still inside the screen, move the pointer
        # If only one of the new coordinates position is inside screen,
        # move just along that coordinate axis.
        # Otherwise don't move
        if pyautogui.onScreen(new_pos):
            pyautogui.moveRel(rel_x, rel_y, duration=self.speed)
        elif 0 <= new_pos[0] <= pyautogui.size()[0]:
            pyautogui.moveRel(rel_x, 0, duration=self.speed)
        elif 0 <= new_pos[1] <= pyautogui.size()[1]:
            pyautogui.moveRel(0, rel_y, duration=self.speed)
Example #15
0
def move(x, y):
    global mouse_x
    global mouse_y
    mouse_x += x
    mouse_y += y
    if gui.onScreen(mouse_x, mouse_y):
        gui.moveTo(mouse_x, mouse_y)
    else:
        if mouse_x < 0:
            mouse_x = 0.0
        if mouse_y < 0:
            mouse_y = 0.0
        dim = gui.size()
        if mouse_x > dim[0]:
            mouse_x = float(dim[0])
        if mouse_y > dim[1]:
            mouse_y = float(dim[1])
        gui.moveTo(mouse_x, mouse_y)
    def template_match(template):

        with mss.mss() as sct:
            mon = sct.monitors[-1]
            img = sct.grab(mon)
        img = np.array(img)
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY)
        A, B = img.shape[::-1]

        template = cv2.imread(template, 0)
        w, h = template.shape[::-1]

        methods = ["cv2.TM_SQDIFF"]
        for meth in methods:
            method = eval(meth)

            # Apply template Matching
            res = cv2.matchTemplate(img, template, method)
            min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

            # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
            if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
                top_left = min_loc
                if min_val > 4041568.0:
                    # print('min_val', min_val)
                    return False

            else:
                top_left = max_loc
                if max_val > 4041568.0:
                    print("ERROR: template not found", max_val)
                    return False

            bottom_right = (top_left[0] + w, top_left[1] + h)

            center = ((top_left[0] + (w / 2)) / 2, (top_left[1] + (h / 2)) / 2)

            if pyautogui.onScreen(center) == True:
                return center
            else:
                print("bad coords error")
                return center
Example #17
0
def updateMouse(dX, dY, buttonPressed):

    if (buttonPressed):
        pyautogui.click()
        return

    screenDim = pyautogui.size()
    #xMultiplier = (screenDim[0] / 224)
    #yMultiplier = (screenDim[1] / 171)
    xMultiplier = 0.5 * ((screenDim[1] / 171) + (screenDim[0] / 224))
    yMultiplier = xMultiplier

    if (dX * xMultiplier > screenDim[0]) or (dY * yMultiplier > screenDim[1]):
        return

    x, y = pyautogui.position()

    if not (pyautogui.onScreen(x + dX * xMultiplier, y + dY * yMultiplier)):
        return

    pyautogui.move(dX * xMultiplier, dY * yMultiplier)
Example #18
0
def click(data):
    try:
        if 'xy' in data:
            x, y = data['xy']
        else:
            x, y = pyautogui.position()
            data['xy'] = x, y
        if pyautogui.onScreen(x, y):
            if 'type' in data and data['type'] == 'двойной':
                pyautogui.doubleClick(x, y)
            else:
                pyautogui.click(x, y)
        else:
            size = pyautogui.size()
            data['error'] = f"Эти координаты ({x}; {y}) " \
                f"находятся вне вашего экрана ({size.width}; {size.height})"
    except KeyError as e:
        data['error'] = f"Требуется аргумент '{e.args[0]}'"
    except Exception as e:
        data['error'] = str(e)
    return data
#-*- coding: utf-8 -*-
import pyautogui as pag

#GUI操作ごとのポーズ秒数
pag.PAUSE = 2.5
x, y = (300, 300)
pag.moveTo(x, y)
print("moveTo メソッドでマウス位置{0}に移動".format((x, y)))
print("画面上にマウス位置は「{0}」".format("ある" if pag.onScreen(x, y) else "ない"))
print("positionメソッドの返り値: {0}".format(pag.position()))

x, y = (1000000, 1000000)
print("moveTo メソッドでマウス位置{0}に移動".format((x, y)))
pag.moveTo(x, y)
print(" 画面上にマウス位置は「{0}」".format("ある" if pag.onScreen(x, y) else "ない"))
print("position メソッドの返り値: {0}".format(pag.position()))
Example #20
0
x, y = gui.position()
print('Current x,y : ' + str(x) + ',' + str(y))

# Paintアプリケーションに描画する
mspaint = application.Application()
mspaint.start('mspaint.exe')
sleep(3)
select = gui.confirm(text='ペイントアプリを画面中央表示して、\n直線を選択してください。',
                     title='確認!',
                     buttons=['OK', 'Cancel'])
if select in 'OK':
    # マウスカーソルの中央への移動
    gui.moveTo(x=(w / 2), y=(h / 2))
    x, y = gui.position()
    print('Point after moving x,y : ' + str(x) + ',' + str(y))
    gui.dragTo(x=(x / 2) + 100, y=(y / 2) + 100, button='left')
    # gui.mouseDown(button='left')
    # gui.mouseUp(button='left',x=(x/2)+100,y=(y/2)+100)

# スクリーン範囲の確認
check = gui.onScreen(100, 100)
if check:
    print('x=100,y=100 ' + 'onScreen')
else:
    print('x=2000,y=3000 ' + 'off onScreen')

gui.alert(text='処理終了', title='確認!', button='OK')

# アプリケーションのプロセスの kill
mspaint.kill()
Example #21
0
import pyautogui

print (pyautogui.size())
print (pyautogui.position())
print (pyautogui.onScreen(pyautogui.position()))


pyautogui.moveTo(400, 400, 10)
Example #22
0
import time, pyautogui, winsound
#import cx_freeze
from random import randint

#pegar o retorno da posicao atual de x e y do mouse e passar o valor da tupla para as duas variaveis
x, y = pyautogui.position()
print("Posicao atual do mouse:")

print("x = " + str(x) + " y = " + str(y))

print("")

#retorna verdadeiro se x & y estiverem dentro da tela
print("Esta dentro da tela?")
resp = pyautogui.onScreen(x, y)
print(str(resp))

n = 0  #numero de curtidas feitas
b = winsound.Beep
pyautogui.click(414, 1057)

#i = randint(30,50) #quantidade de fotos a serem curtidas
i = 500
intervalo = randint(5, 10)  #intervalo entre as curtidas

while (i != 0):
    time.sleep(1)
    pyautogui.click(1077, 670)
    time.sleep(4)
    pyautogui.click(804, 764)
    time.sleep(40)
Example #23
0
 def onScreen(self, x, y):
     from pyautogui import onScreen
     response = onScreen(x, y)
     return response
 def do(self, event):
     super().do(event)
     assert isinstance(event["event_key"], mouse.Button)
     assert onScreen(event["position_x"], event["position_y"])
     return event
    def control_pc(self, pre_gesture, now_gesture, head):
        if pre_gesture == now_gesture:
            pass

        else:
            if now_gesture == 'Thumb Up':
                # browser open
                # if self.my_tab_num == -1:
                #     self.browser = webdriver.Chrome(chrome_options=self.options, executable_path = './chromedriver')
                #     self.browser.set_window_position(self.screenW//2, 0)
                #     self.browser.set_window_size(self.screenW//2, self.screenH)
                #     self.browser.get('http://google.com')
                #     self.tabs = self.browser.window_handles
                #     self.my_tab_num += 1
                # else:
                #     self.browser.execute_script('window.open("http://google.com", "_blank");')
                #     self.tabs = self.browser.window_handles
                #     self.my_tab_num =len(self.browser.window_handles) + 1
                # click
                pg.click()
                pass

            elif now_gesture == 'Sliding Two Fingers Up':
                # mouse up
                cur_x, cur_y = pg.position()
                pg.moveTo(cur_x, cur_y - 100, 1)
                if not pg.onScreen(cur_x, cur_y - 100):
                    pg.moveTo(cur_x, 0)

            elif now_gesture == 'Stop Sign':
                # exit
                # self.tabs = self.browser.window_handles
                # for i in range(self.my_tab_num, -1, -1):
                #     self.browser.switch_to_window(self.tabs[i])
                #     self.browser.close()
                # self.browser = None
                # self.tabs = None
                # self.my_tab_num = 0
                pass

            elif now_gesture == 'Swiping Right':
                # mouse righr fast
                cur_x, cur_y = pg.position()
                pg.moveTo(cur_x + 250, cur_y, 1)
                if not pg.onScreen(cur_x + 250, cur_y):
                    pg.moveTo(self.screenW, cur_y)

            elif now_gesture == 'Swiping Left':
                # mouse left fast
                cur_x, cur_y = pg.position()
                pg.moveTo(cur_x - 250, cur_y, 1)
                if not pg.onScreen(cur_x - 250, cur_y):
                    pg.moveTo(0, cur_y)

            elif now_gesture == 'Sliding Two Fingers Right':
                # mouse right
                cur_x, cur_y = pg.position()
                pg.moveTo(cur_x + 100, cur_y, 1)
                if not pg.onScreen(cur_x + 100, cur_y):
                    pg.moveTo(self.screenW, cur_y)

            elif now_gesture == 'Sliding Two Fingers Left':
                # mouse left
                cur_x, cur_y = pg.position()
                pg.moveTo(cur_x - 100, cur_y, 1)
                if not pg.onScreen(cur_x - 100, cur_y):
                    pg.moveTo(0, cur_y)

            elif now_gesture == 'Sliding Two Fingers Down':
                # mouse down
                cur_x, cur_y = pg.position()
                pg.moveTo(cur_x, cur_y + 100, 1)
                if not pg.onScreen(cur_x, cur_y + 100):
                    pg.moveTo(cur_x, self.screenH)

            elif now_gesture == 'Swiping Up':
                # close tab
                # self.browser.switch_to_window(self.tabs[self.my_tab_num])
                # self.browser.close()
                # self.my_tab_num += -1
                # if self.my_tab_num<0:
                #     self.my_tab_num = 0
                # scroll Down
                pg.scroll(10)

            elif now_gesture == 'Swiping Down':
                # scroll Up
                pg.scroll(-10)

            elif now_gesture == 'Rolling Hand Backward':
                # go back
                #self.browser.back()

                pass

            else:
                #
                pass
Example #26
0
    def test_onScreen(self):
        zero = P(0, 0)
        xone = P(1, 0)
        yone = P(0, 1)
        size = P(*pyautogui.size())
        half = size / 2

        on_screen = [
            zero,
            zero + xone,
            zero + yone,
            zero + xone + yone,
            half,
            size - xone - yone,
        ]
        off_screen = [
            zero - xone,
            zero - yone,
            zero - xone - yone,
            size - xone,
            size - yone,
            size,
        ]

        for value, coords in [(True, on_screen), (False, off_screen)]:
            for coord in coords:
                self.assertEqual(value, pyautogui.onScreen(*coord), 'onScreen({0}, {1}) should be {2}'.format(coord.x, coord.y, value))
                self.assertEqual(value, pyautogui.onScreen(list(coord)), 'onScreen([{0}, {1}]) should be {2}'.format(coord.x, coord.y, value))
                self.assertEqual(value, pyautogui.onScreen(tuple(coord)), 'onScreen(({0}, {1})) should be {2}'.format(coord.x, coord.y, value))
                self.assertEqual(value, pyautogui.onScreen(coord), 'onScreen({0}) should be {1}'.format(repr(coord), value))

        # These can raise either ValueError or TypeError.
        with self.assertRaises(ValueError):
            pyautogui.onScreen([0, 0], 0)
        with self.assertRaises(ValueError):
            pyautogui.onScreen((0, 0), 0)
        with self.assertRaises(TypeError):
            pyautogui.onScreen(0, 0, 0)
        with self.assertRaises(TypeError):
            pyautogui.onScreen(0)
 def do(self, event):
     super().do(event)
     assert onScreen(event["position_x"], event["position_y"])
     return event
Example #28
0
 def move(self, x, y):
     current_x, current_y = pyautogui.position()
     dist_x = x * self.precision
     dist_y = -1 * y * self.precision
     if (pyautogui.onScreen(current_x + dist_x, current_y + dist_y)):
         pyautogui.moveRel(dist_x, dist_y, duration=self.speed)
import pyautogui

print(pyautogui.size())  # current screen resolution width and height
print(pyautogui.position())  # current mouse x and y
print(pyautogui.onScreen(500, 500))  # True if x & y are within the screen.
pyautogui.PAUSE = 2  # Set up a 2 second pause after each PyAutoGUI call:

#Mouse Functions:
pyautogui.moveTo(x, y, duration=num_seconds
                 )  # move mouse to XY coordinates over num_second seconds
pyautogui.moveRel(
    xOffset, yOffset,
    duration=num_seconds)  # move mouse relative to its current position

pyautogui.dragTo(x, y, duration=num_seconds)  # drag mouse to XY
pyautogui.dragRel(
    xOffset, yOffset,
    duration=num_seconds)  # drag mouse relative to its current position

pyautogui.rightClick(x=moveToX, y=moveToY)  #go to XY and rightClick
pyautogui.middleClick(x=moveToX, y=moveToY)
pyautogui.doubleClick(x=moveToX, y=moveToY)
pyautogui.tripleClick(x=moveToX, y=moveToY)

pyautogui.scroll(amount_to_scroll, x=moveToX, y=moveToY)
print(pyautogui.position())
pyautogui.click(1341, 331)
pyautogui.scroll(10)  # scroll up 10 "clicks"
pyautogui.scroll(-10)  # scroll down 10 "clicks"

pyautogui.scroll(
Example #30
0
    def test_onScreen(self):
        zero = P(0, 0)
        xone = P(1, 0)
        yone = P(0, 1)
        size = P(*pyautogui.size())
        half = size / 2

        on_screen = [
            zero,
            zero + xone,
            zero + yone,
            zero + xone + yone,
            half,
            size - xone - yone,
        ]
        off_screen = [
            zero - xone,
            zero - yone,
            zero - xone - yone,
            size - xone,
            size - yone,
            size,
        ]

        for value, coords in [(True, on_screen), (False, off_screen)]:
            for coord in coords:
                self.assertEqual(
                    value, pyautogui.onScreen(*coord),
                    'onScreen({0}, {1}) should be {2}'.format(
                        coord.x, coord.y, value))
                self.assertEqual(
                    value, pyautogui.onScreen(list(coord)),
                    'onScreen([{0}, {1}]) should be {2}'.format(
                        coord.x, coord.y, value))
                self.assertEqual(
                    value, pyautogui.onScreen(tuple(coord)),
                    'onScreen(({0}, {1})) should be {2}'.format(
                        coord.x, coord.y, value))
                self.assertEqual(
                    value, pyautogui.onScreen(coord),
                    'onScreen({0}) should be {1}'.format(repr(coord), value))

        # These can raise either ValueError or TypeError.
        with self.assertRaises(ValueError):
            pyautogui.onScreen([0, 0], 0)
        with self.assertRaises(ValueError):
            pyautogui.onScreen((0, 0), 0)
        with self.assertRaises(TypeError):
            pyautogui.onScreen(0, 0, 0)
        with self.assertRaises(TypeError):
            pyautogui.onScreen(0)
Example #31
0
    def test_onScreen(self):
        width, height = pyautogui.size()
        halfWidth = int(width / 2)
        halfHeight = int(height / 2)

        self.assertTrue(pyautogui.onScreen(0, 0))
        self.assertTrue(pyautogui.onScreen([0, 0]))

        self.assertTrue(pyautogui.onScreen(halfWidth, 0))
        self.assertTrue(pyautogui.onScreen([halfWidth, 0]))
        self.assertTrue(pyautogui.onScreen(0, halfHeight))
        self.assertTrue(pyautogui.onScreen([0, halfHeight]))
        self.assertTrue(pyautogui.onScreen(halfWidth, halfHeight))
        self.assertTrue(pyautogui.onScreen([halfWidth, halfHeight]))

        self.assertFalse(pyautogui.onScreen(-1, 0))
        self.assertFalse(pyautogui.onScreen([-1, 0]))
        self.assertFalse(pyautogui.onScreen(-1, -1))
        self.assertFalse(pyautogui.onScreen([-1, -1]))
        self.assertFalse(pyautogui.onScreen(0, -1))
        self.assertFalse(pyautogui.onScreen([0, -1]))

        self.assertFalse(pyautogui.onScreen(width, 0))
        self.assertFalse(pyautogui.onScreen([width, 0]))
        self.assertFalse(pyautogui.onScreen(0, height))
        self.assertFalse(pyautogui.onScreen([0, height]))
        self.assertFalse(pyautogui.onScreen(width, height))
        self.assertFalse(pyautogui.onScreen([width, height]))
Example #32
0
# conda install -c conda-forge pyautogui
# Ref: [PyAutoGUI Cheet Sheet](https://pyautogui.readthedocs.io/en/latest/quickstart.html)

import pyautogui

print(pyautogui.position())
# Point(x=754, y=1057) position of chrome link
x = 800
y = 1060
print(pyautogui.size())
print(pyautogui.onScreen(800, 1060))
pyautogui.moveTo(x, y, duration=3)
moveToX = 831
moveToY = 1048
pyautogui.click(x=moveToX, y=moveToY, clicks=1, button='left')
x = 579
y = 612
pyautogui.moveTo(x, y, duration=5)
moveToX = 699
moveToY = 74
pyautogui.click(x=moveToX, y=moveToY, clicks=1, button='left')
pyautogui.hotkey('shift')
pyautogui.typewrite('Python',
                    interval=0.2)  # useful for entering text, newline is Enter
pyautogui.hotkey('shift')
pyautogui.typewrite('w94\ngp6\nx87\n\n', interval=0.2)
'''
lecture2_example10.py. This example first imports the pyautogui module. It
then 1) returns the mouse's position on the screen; 2) return's the screen's
resolution; and 3) tests whether a given coordinate is located on the screen. 
'''

import pyautogui

pyautogui.PAUSE = 3
pyautogui.position()
pyautogui.size()
pyautogui.onScreen(3000, 3000)
pyautogui.onScreen(500, 500)
Example #34
0
pg.KEYBOARD_KEYS
# получение списка клавиш



# general :::::::::::::::::::::::::::::::::::::::::::::::::::::::::

pg.size()
# возвращает кортеж из двух целых чисел, представляющих ширину и 
# высоту экрана в пикселях

pg.position()
# возвращает кортеж из двух целых чисел, представляющих координаты
# текущей позиции указателя

pg.onScreen(x, y)
# возвращает True если x и y находятся в пределах экрана

pg.pixelMatchesColor(x, y, 'RGBA', tolerance=10)
# возвращает значение True, если цвет пикселя с заданными экранными
# координатами x и y совпадают с заданным цветом
# tolerance задаёт насколько каждый цвет может не совподать



# screenshot ::::::::::::::::::::::::::::::::::::::::::::::::::::::

pg.screenshot('ex.png', region=(x,y, width, height))
# делает снимок экрана. Необзательный аргумент файл, если требуется
# задать имя. region необязательный аргумент, область захвата
	getpixel((x, y))