品易云推流 关闭
文章详情页
文章 > Python基础教程 > python模拟点击中如何实现区域的不同按键?

python模拟点击中如何实现区域的不同按键?

头像

小妮浅浅

2020-11-26 11:35:302238浏览 · 0收藏 · 0评论

当我们想要在某一点、某一位置重复步骤,这些不同位置上的相同操作对于小伙伴们来说都不是问题。但在实际的运用中,我们需要对不同位置点进行不同的按键操作,每一个位置需要不同的任务需求,这就比之前的单个任务目标要难得多。今天小编先跟大家讲一下操作的思路,再进行代码模块的试验相信就不会那么困难了。


假如想要实现鼠标左键双击时根据所在的不同区域实现不同的自动按键。

 

思路:监控鼠标事件,判断按键类型,如果是判断双击保留上一次的点击时间,自动按键最好新建线程,不然会卡在主线程。

#coding=utf-8
 
from pymouse import PyMouse, PyMouseEvent
from pykeyboard import PyKeyboard, PyKeyboardEvent
import time, threading
import math
 
## 初始化参数区(全局变量)
stop = False
interval = 1
is_running = False
times = 10
keys_mapping = {
    0 : ['1', '2', '3', '4'],
    10 : ['a', 'b'],
    1 : ['c', 'd'],
    11 : ['e', 'f'],
}   # 左上:0 右上:10 左下:1 右下:11
mouse = PyMouse()
keyboard = PyKeyboard()
x_dim, y_dim = mouse.screen_size()
 
## 循环按键
def loop(key):
    global stop
    global is_running
    global keyboard
    is_running = True
    for i in range(times):
        for k in keys_mapping[key]:
            if stop:
                print('stop')
                is_running = False
                return
            print(key, k)
            #keyboard.tap_key(k)
            time.sleep(interval)
    is_running = False
 
## 监控鼠标
class Clickonacci(PyMouseEvent):
    last_ts = None
    last_x = None
    last_y = None
    last_button = None
 
    def __init__(self):
        PyMouseEvent.__init__(self)
 
    ## hori:1-上,-1-下
    def scroll(self, x, y, hori, press):
        print(x, y, hori)
 
    def click(self, x, y, button, press):
        if press:
            return
        global stop
        global x_dim
        global y_dim
        ts = time.time()
        # button:1-左键,2-右键,3-中键
        # press: True-按下,False-释放
        if button == 1:
            ## 判断双击
            if self.last_ts and ts-self.last_ts<0.3 and self.last_button==button:
                print('double click')
                if is_running == True:
                    stop = True
                    time.sleep(interval)
                stop = False
                ## 计算类型
                key = 10*math.floor(2.0*x/x_dim) + math.floor(2.0*y/y_dim)
                t = threading.Thread(target=loop, name='LoopThread', args=(key,))
                t.start()
            self.last_ts = ts
            self.last_x = x
            self.last_y = y
            self.last_button = button
        else:
            stop = True
 
if __name__ == '__main__':
    #main()
    C = Clickonacci()
    C.run()


本篇的代码模块比较复杂,因为涉及到了不同位置要实现不同按键的操作。小伙伴们在代码模块可以先拆分进行理解和学习,在跟着小编的思路进行整体代码的理解就好啦~更多Python学习指路:PyThon学习网教学中心


关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图