pyautogui按键跟随,auto clicker解放双手

发布于:2024-11-27 ⋅ 阅读:(132) ⋅ 点赞:(0)

试图实现简化重复性手动操作,解放双手。录制一次手动操作流程,后续自动复现该操作。
其中一个程序用于记录坐标们,坐标点保存在文档中,然后另一个程序再取文档中的坐标,进行鼠标自动点击。


pyautogui获取坐标和点击坐标

import pyautogui
x, y = pyautogui.position() # 获取鼠标当前位置的坐标
print(f"当前鼠标位置的坐标为:({x}, {y})")
pyautogui.click(x, y) # 点击坐标

环境配置

安装可能需要用到的库

pip install pyautogui pynput

pynput记录坐标

原本用的pyautogui计时刷新,后来改点击时记录坐标

  • 加入pynput库,用pynput.mouse.listener来监听鼠标单击事件,而不是连续地检查鼠标状态。
  • 使用a模式追加坐标,不要覆盖原有,with open(file_name, 'a') as f:.
  • 录制开始时,如果坐标文档已存在,进行清除的步骤.
  • 录制停止时,不再记录坐标入文档,且删除最后记录的坐标(即,停止按钮单击的坐标)。
import os
import threading
import tkinter as tk
from tkinter import messagebox
from pynput import mouse
recording = False
file_name = 'mouse_clicks.txt'
def on_click(x, y, button, pressed):
    if pressed and recording:  # Only log when the mouse button is pressed and recording is active
        with open(file_name, 'a') as f:  # Append to the file
            f.write(f"{x},{y}\n")
        print(f"Recorded click at: ({x}, {y})")
def start_recording():
    global recording
    recording = True
    if os.path.exists(file_name):
        user_input = messagebox.askyesno("File Exists", f"{file_name} already exists. Do you want to clear it?")
        if user_input:
            os.remove(file_name)
            print(f"{file_name} has been cleared.")
    print("Started recording...")
    # Start the mouse listener
    listener = mouse.Listener(on_click=on_click)
    listener.start()  # Start the listener in a non-blocking way
    listener.join()  # Keep the listener running
def stop_recording():
    global recording
    recording = False
    # Remove the last line from the file if it exists, which contains the last click
    try:
        with open(file_name, 'r+') as f:
            lines = f.readlines()
            if lines:  # Check if there are lines in the file
                # Move file pointer to the start
                f.seek(0)
                # Write all lines except the last one
                f.writelines(lines[:-1])
                # Truncate the file to the new size
                f.truncate()
        print("Recording stopped. Last click removed.")
    except FileNotFoundError:
        print(f"Error: {file_name} not found.")
    except Exception as e:
        print(f"An error occurred: {e}")
def on_start():
    threading.Thread(target=start_recording, daemon=True).start()
# Create main window
root = tk.Tk()
root.title("Mouse Click Recorder")
# Create buttons
start_button = tk.Button(root, text="Start Recording", command=on_start)
start_button.pack(pady=10)
stop_button = tk.Button(root, text="Stop Recording", command=stop_recording)
stop_button.pack(pady=10)
# Run the main loop
root.mainloop()

pyautogui复现动作

从mouse clicks.txt中读取坐标,并以0.5秒的时间间隔在这些位置上自动单击。【interval=0.5可能需要调整,根据实际情况,有的时候0.5会太快了,有的时候可以速度更快】

import time
import pyautogui
file_name = 'mouse_clicks.txt'
def read_clicks(file_name):
    clicks = []
    try:
        with open(file_name, 'r') as f:
            for line in f:
                x, y = map(int, line.strip().split(','))
                clicks.append((x, y))
    except FileNotFoundError:
        print(f"Error: {file_name} not found.")
    return clicks
def auto_click(clicks, interval=0.5):
    print("Starting auto clicker...")
    for (x, y) in clicks:
        pyautogui.click(x, y)
        print(f"Clicked at: ({x}, {y})")
        time.sleep(interval)
if __name__ == "__main__":
    clicks = read_clicks(file_name)
    if clicks:
        auto_click(clicks)
    else:
        print("No clicks to perform.")

运行效果

pyautogui按键跟随,auto clicker解放双手

功能改进

防止多个侦听器:
每次开始录制时,都会创建一个新的侦听器线程,即使在停止之前的录制之后,该线程也会继续运行。多次开始和停止记录时,当再次调用start recording时,可能会导致多个侦听器同时处于活动状态,导致多次记录相同的单击。
在这里插入图片描述
因此,修改以确保在任何给定时间只有一个鼠标侦听器处于活动状态。使用全局变量跟踪侦听器线程,并在停止录制时适当地停止它。

from pynput import mouse
recording = False
listener = None  # A global variable to hold the listener instance

def start_recording():
    global recording, listener

    # Start the mouse listener only if it's not already running
    if listener is None or not listener.is_alive():
        listener = mouse.Listener(on_click=on_click)
        listener.start()  # Start the listener in a non-blocking way
def stop_recording():
    global recording, listener
    
    if listener is not None:
        listener.stop()  # Stop the listener
        listener.join()  # Wait for the listener thread to finish
        listener = None  # Reset the listener to allow for a new one on the next start

pyautogui复现动作升级,通过pynput记录坐标,录制很多个步骤的操作动作坐标,多个pyautogui复现动作聚合在一起,点按钮就可以执行相应的一系列鼠标动作。
使用 tkinter 创建一个简单的窗口,包含一个标签、一个下拉菜单和一个按钮。然后选择想要的文本文件,点击“Start Auto Clicker”按钮开始自动点击。
在这里插入图片描述
在这里插入图片描述

import os
import time
import pyautogui
import tkinter as tk
from tkinter import ttk, messagebox
def read_clicks(file_name):
    clicks = []
    try:
        with open(file_name, 'r') as f:
            for line in f:
                x, y = map(int, line.strip().split(','))
                clicks.append((x, y))
    except FileNotFoundError:
        messagebox.showerror("Error", f"{file_name} not found.")
    return clicks
def auto_click(clicks, interval=1):
    print("Starting auto clicker...")
    for (x, y) in clicks:
        pyautogui.click(x, y)
        print(f"Clicked at: ({x}, {y})")
        time.sleep(interval)
def on_start_click():
    file_name = combo.get()
    if file_name:
        clicks = read_clicks(file_name)
        if clicks:
            auto_click(clicks)
        else:
            messagebox.showwarning("Warning", "No clicks to perform.")
    else:
        messagebox.showwarning("Warning", "Please select a file.")
def load_files():
    # Load all .txt files in the current directory
    files = [f for f in os.listdir('.') if f.endswith('.txt')]
    return files
# Create the main window
root = tk.Tk()
root.title("Auto Clicker")
# Create a label
label = tk.Label(root, text="Select a file:")
label.pack(pady=10)
# Create a dropdown menu
combo = ttk.Combobox(root, values=load_files())
combo.pack(pady=10)
# Create a start button
start_button = tk.Button(root, text="Start Auto Clicker", command=on_start_click)
start_button.pack(pady=20)
# Run the application
root.mainloop()

网站公告

今日签到

点亮在社区的每一天
去签到