自动键盘工具 v1.0
功能:
– 带GUI界面的自动键盘按键工具
– 支持设置要按下的按键、基础间隔时间和随机延时
– F10快捷键启动/停止自动按键
– 防检测机制:随机按键时间和可变间隔时间
– 可点击的官网链接
使用库:
– tkinter: GUI界面开发
– pynput: 键盘控制和监听
– threading: 多线程处理
– logging: 日志记录
– webbrowser: 网页链接处理
“””
import tkinter as tk
from tkinter import ttk, messagebox
import threading
import time
import random
import logging
import webbrowser
from pynput import keyboard
import urllib.request
# 配置日志系统
# 日志将同时输出到文件(auto_keyboard.log)和控制台
logging.basicConfig(
level=logging.DEBUG, # 日志级别:DEBUG(详细)、INFO、WARNING、ERROR、CRITICAL
format=’%(asctime)s – %(levelname)s – %(message)s’, # 日志格式
handlers=[
logging.FileHandler(‘auto_keyboard.log’), # 日志文件
logging.StreamHandler() # 控制台输出
]
)
class AutoKeyboardTool:
“””自动键盘工具主类
负责创建GUI界面、处理用户输入、管理快捷键监听和自动按键线程
“””
def __init__(self, root):
“””初始化方法
参数:
root: tkinter.Tk – 主窗口实例
“””
self.root = root
self.root.title(“自动键盘工具”) # 设置窗口标题
self.root.geometry(“400×450”) # 设置窗口尺寸和位置 (宽度x高度+X坐标+Y坐标)
self.root.resizable(True, True) # 允许窗口调整大小
# 确保窗口在顶层且可见
self.root.lift()
self.root.attributes(‘-topmost’, True)
self.root.attributes(‘-topmost’, False)
# 设置窗口图标(如果有icon.ico文件,可以取消注释)
# self.root.iconbitmap(‘icon.ico’)
# 变量初始化
self.is_running = False # 自动按键运行状态
self.key_to_press = tk.StringVar(value=’1′) # 要按下的按键
self.interval = tk.DoubleVar(value=1.0) # 基础间隔时间(秒)
self.random_delay = tk.DoubleVar(value=0.2) # 随机延时范围(秒)
# 创建UI组件
self.create_widgets()
# 快捷键监听器相关变量
self.listener_thread = None # 监听线程
self.listener = None # 监听器实例
# 自动按键线程
self.key_thread = None # 按键线程
# 启动快捷键监听
self.start_listener()
# 绑定窗口关闭事件
self.root.protocol(“WM_DELETE_WINDOW”, self.on_close)
def create_widgets(self):
“””创建所有UI组件”””
# 创建主框架
# padding=”20″表示框架内边距为20像素
main_frame = ttk.Frame(self.root, padding=”20″)
# fill=tk.BOTH表示框架填充父容器的宽度和高度
# expand=True表示框架会随窗口大小变化而扩展
main_frame.pack(fill=tk.BOTH, expand=True)
# 添加官网链接 – 放在标题下方
def open_website():
“””打开官网链接”””
webbrowser.open(“https://www.youres.cn”)
# 创建可点击的链接标签
website_frame = ttk.Frame(main_frame)
website_frame.pack(fill=tk.X, pady=5)
self.website_label = tk.Label(website_frame, text=”官网链接: www.youres.cn”,
fg=”blue”, cursor=”hand2″, font=(“Arial”, 10))
# 居中显示链接
self.website_label.pack(fill=tk.X, pady=5)
# 绑定鼠标点击事件,点击时打开官网
self.website_label.bind(“<Button-1>”, lambda e: open_website())
# 按键设置区域
# ttk.LabelFrame创建带标题的框架
key_frame = ttk.LabelFrame(main_frame, text=”按键设置”, padding=”10″)
# fill=tk.X表示框架填充父容器的宽度
# pady=5表示上下外边距为5像素
key_frame.pack(fill=tk.X, pady=5)
# 创建标签和输入框
ttk.Label(key_frame, text=”按键: “).grid(row=0, column=0, sticky=tk.W, pady=5)
self.key_entry = ttk.Entry(key_frame, textvariable=self.key_to_press, width=10)
# grid布局:row=0行, column=0列, sticky=tk.W左对齐, pady=5上下边距
self.key_entry.grid(row=0, column=1, sticky=tk.W, pady=5)
# 间隔设置区域
interval_frame = ttk.LabelFrame(main_frame, text=”间隔设置”, padding=”10″)
interval_frame.pack(fill=tk.X, pady=5)
# 基础间隔设置
ttk.Label(interval_frame, text=”基础间隔 (秒): “).grid(row=0, column=0, sticky=tk.W, pady=5)
# Spinbox创建数值选择器
# from_=0.1最小值, to=10.0最大值, increment=0.1步长
self.interval_spinbox = ttk.Spinbox(interval_frame, from_=0.1, to=10.0, increment=0.1,
textvariable=self.interval, width=10)
self.interval_spinbox.grid(row=0, column=1, sticky=tk.W, pady=5)
# 随机延时设置
ttk.Label(interval_frame, text=”随机延时 (秒): “).grid(row=1, column=0, sticky=tk.W, pady=5)
self.delay_spinbox = ttk.Spinbox(interval_frame, from_=0.0, to=2.0, increment=0.1,
textvariable=self.random_delay, width=10)
self.delay_spinbox.grid(row=1, column=1, sticky=tk.W, pady=5)
# 状态显示区域
status_frame = ttk.LabelFrame(main_frame, text=”状态”, padding=”10″)
status_frame.pack(fill=tk.X, pady=5)
# 状态标签,显示当前运行状态
self.status_label = ttk.Label(status_frame, text=”就绪 (按F10启动/停止)”,
foreground=”green”, font=(“Arial”, 10, “bold”))
self.status_label.pack(fill=tk.X, pady=5)
# 按钮区域
button_frame = ttk.Frame(main_frame, padding=”10″)
button_frame.pack(fill=tk.X, pady=10)
# 启动按钮
self.start_button = ttk.Button(button_frame, text=”启动”, command=self.start_auto_keyboard)
# side=tk.LEFT表示按钮从左向右排列
# padx=5表示左右外边距为5像素
# fill=tk.X表示按钮填充父容器宽度
# expand=True表示按钮会扩展以填充可用空间
self.start_button.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
# 停止按钮
self.stop_button = ttk.Button(button_frame, text=”停止”, command=self.stop_auto_keyboard)
self.stop_button.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
# 切换按钮
self.toggle_button = ttk.Button(button_frame, text=”切换 (F10)”, command=self.toggle_auto_keyboard)
self.toggle_button.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
# 添加官网链接 – 直接添加到root窗口底部
def on_press(self, key):
“””快捷键按下事件处理
参数:
key: pynput.keyboard.Key或pynput.keyboard.KeyCode – 按下的按键
“””
try:
# 检查是否按下F10键
if key == keyboard.Key.f10:
self.toggle_auto_keyboard() # 切换自动按键状态
except Exception as e:
logging.error(f”快捷键处理错误: {e}”)
def start_listener(self):
“””启动快捷键监听器
创建并启动一个独立线程来监听全局快捷键
“””
try:
# 创建键盘监听器实例,指定按键处理函数
self.listener = keyboard.Listener(on_press=self.on_press)
# 创建线程,设置daemon=True表示线程会随主程序退出而结束
self.listener_thread = threading.Thread(target=self.listener.start, daemon=True)
# 启动线程
self.listener_thread.start()
logging.info(“快捷键监听器已启动”)
except Exception as e:
logging.error(f”启动快捷键监听器错误: {e}”)
# 显示错误对话框
messagebox.showerror(“错误”, f”无法启动快捷键监听: {e}”)
def start_auto_keyboard(self):
“””启动自动按键功能
如果已经在运行,则直接返回
否则创建并启动自动按键线程
“””
if self.is_running:
return # 如果已经在运行,不重复启动
try:
self.is_running = True # 设置运行状态为True
# 更新状态标签
self.status_label.config(text=”运行中 (按F10停止)”, foreground=”red”)
# 创建自动按键线程
self.key_thread = threading.Thread(target=self.auto_key_press, daemon=True)
self.key_thread.start() # 启动线程
logging.info(“自动按键已启动”)
except Exception as e:
logging.error(f”启动自动按键错误: {e}”)
messagebox.showerror(“错误”, f”无法启动自动按键: {e}”)
# 出错时恢复状态
self.is_running = False
self.status_label.config(text=”就绪 (按F10启动/停止)”, foreground=”green”)
def stop_auto_keyboard(self):
“””停止自动按键功能
如果没有在运行,则直接返回
否则停止自动按键线程并更新状态
“””
if not self.is_running:
return # 如果没有在运行,直接返回
self.is_running = False # 设置运行状态为False
# 更新状态标签
self.status_label.config(text=”就绪 (按F10启动/停止)”, foreground=”green”)
logging.info(“自动按键已停止”)
def toggle_auto_keyboard(self):
“””切换自动按键功能的运行状态
如果正在运行,则停止
如果没有运行,则启动
“””
if self.is_running:
self.stop_auto_keyboard() # 如果正在运行,停止
else:
self.start_auto_keyboard() # 如果没有运行,启动
def auto_key_press(self):
“””自动按键核心功能
循环模拟按键操作,包含防检测机制:
– 随机按键按下时间 (0.05-0.15秒)
– 可变间隔时间 (基础间隔 ± 随机延时)
“””
# 创建键盘控制器实例
controller = keyboard.Controller()
# 当运行状态为True时持续按键
while self.is_running:
try:
# 获取用户设置的参数
key = self.key_to_press.get().strip() # 要按下的按键
base_interval = self.interval.get() # 基础间隔时间
random_delay = self.random_delay.get() # 随机延时范围
# 如果没有设置按键,等待0.1秒后继续
if not key:
time.sleep(0.1)
continue
# 防检测机制1:随机按键按下时间 (0.05-0.15秒)
# 模拟人类按键的不确定性
key_press_time = random.uniform(0.05, 0.15)
# 防检测机制2:生成随机间隔时间
actual_interval = base_interval
if random_delay > 0:
# 在基础间隔上添加随机偏移量
actual_interval = base_interval + random.uniform(-random_delay, random_delay)
# 确保间隔不小于0.05秒,避免过快按键
actual_interval = max(0.05, actual_interval)
# 模拟按键操作
if len(key) == 1:
# 普通按键 (如 ‘1’, ‘a’, ‘!’)
controller.press(key) # 按下按键
time.sleep(key_press_time) # 保持按下状态
controller.release(key) # 释放按键
else:
# 尝试特殊按键 (如 ‘space’, ‘enter’, ‘ctrl’)
try:
# 获取特殊按键对象
special_key = getattr(keyboard.Key, key)
controller.press(special_key)
time.sleep(key_press_time)
controller.release(special_key)
except AttributeError:
# 如果不是特殊按键,按字符串中的每个字符
for char in key:
controller.press(char)
# 按比例分配按键时间
time.sleep(key_press_time / len(key))
controller.release(char)
# 计算下一次按键的等待时间
# 减去按键本身占用的时间,确保总间隔符合用户设置
wait_time = actual_interval – key_press_time
if wait_time > 0:
time.sleep(wait_time)
except Exception as e:
logging.error(f”自动按键错误: {e}”)
time.sleep(1) # 出错时等待1秒再继续,避免频繁报错
def on_close(self):
“””窗口关闭事件处理
确保在窗口关闭时正确清理资源:
– 停止自动按键
– 停止快捷键监听
– 等待线程结束
– 从网络文本读取地址并打开
– 销毁窗口
“””
self.is_running = False # 停止自动按键
# 停止快捷键监听
if self.listener:
try:
self.listener.stop()
except Exception as e:
logging.error(f”停止监听器错误: {e}”)
# 等待线程结束,设置timeout=0.5秒避免无限等待
if self.listener_thread and self.listener_thread.is_alive():
self.listener_thread.join(timeout=0.5)
if self.key_thread and self.key_thread.is_alive():
self.key_thread.join(timeout=0.5)
# 关闭软件时从网络文本读取地址并打开
try:
# 设置网络文本地址(用户可以根据需要修改)
network_text_url = “https://www.youres.cn/dz.txt”
# 配置网络请求超时时间为3秒
timeout = 3
# 创建请求对象并添加浏览器请求头,避免被服务器拒绝
req = urllib.request.Request(network_text_url)
req.add_header(‘User-Agent’, ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36’)
req.add_header(‘Accept’, ‘text/plain, */*’)
req.add_header(‘Connection’, ‘keep-alive’)
# 发送网络请求并读取内容
logging.info(f”正在请求网络文本: {network_text_url}”)
with urllib.request.urlopen(req, timeout=timeout) as response:
# 检查响应状态码
if response.status != 200:
logging.error(f”网络请求返回错误状态码: {response.status}”)
# 使用默认链接
default_url = “https://www.youres.cn”
webbrowser.open(default_url)
logging.info(f”请求失败,已打开默认链接: {default_url}”)
return
content = response.read().decode(‘utf-8’).strip()
logging.info(f”成功读取网络文本内容: {content}”)
# 检查内容是否为有效的URL格式
if content.startswith((‘http://’, ‘https://’)):
# 打开从网络文本读取的URL
webbrowser.open(content)
logging.info(f”已打开从网络读取的链接: {content}”)
else:
# 如果不是有效的URL,使用默认链接
default_url = “https://www.youres.cn”
webbrowser.open(default_url)
logging.info(f”网络文本内容不是有效的URL,已打开默认链接: {default_url}”)
except urllib.error.URLError as e:
# 网络请求失败时使用默认链接
logging.error(f”网络请求错误: {e}”)
if hasattr(e, ‘code’):
logging.error(f”HTTP错误代码: {e.code}”)
if hasattr(e, ‘reason’):
logging.error(f”错误原因: {e.reason}”)
default_url = “https://www.youres.cn”
webbrowser.open(default_url)
logging.info(f”网络请求失败,已打开默认链接: {default_url}”)
except urllib.error.HTTPError as e:
# 处理HTTP错误
logging.error(f”HTTP请求错误: {e.code} – {e.reason}”)
default_url = “https://www.youres.cn”
webbrowser.open(default_url)
logging.info(f”HTTP请求失败,已打开默认链接: {default_url}”)
except Exception as e:
# 其他错误时使用默认链接
logging.error(f”打开链接错误: {e}”)
logging.error(f”错误类型: {type(e).__name__}”)
import traceback
logging.error(f”完整错误信息: {traceback.format_exc()}”)
default_url = “https://www.youres.cn”
webbrowser.open(default_url)
logging.info(f”发生错误,已打开默认链接: {default_url}”)
logging.info(“程序已退出”)
self.root.destroy() # 销毁窗口
def main():
“””主函数
程序入口点,创建并运行自动键盘工具
“””
try:
logging.info(“自动键盘工具启动”)
# 创建主窗口实例
root = tk.Tk()
# 显示窗口并确保它可见
root.update_idletasks()
root.deiconify()
# 创建自动键盘工具实例
app = AutoKeyboardTool(root)
logging.info(“GUI界面创建完成,进入主事件循环”)
# 启动主事件循环
root.mainloop()
logging.info(“主事件循环结束”)
except Exception as e:
# 记录严重错误
logging.critical(f”程序启动错误: {e}”)
# 显示错误对话框
messagebox.showerror(“严重错误”, f”程序无法启动: {e}”)
# 程序入口
if __name__ == “__main__”:
main()
成品下载地址:键盘按键助手小工具
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...
冀公网安备13073102000141号