小友第一次在本版发帖,结合Ai生成的宏录制,鼠标连点的辅助软件

查看 80|回复 9
作者:忆惘惜   
各位大佬,各位道友好!!!
       小友刚开始学习使用Ai生成Python代码,并生成可执行的软件,软件目前存在已知2处问题,尝试Ai反复修改仍未解决,所以想听听各位大佬及道友的见解。
问题1:在软件按键操作页签,我添加了捕捉用户按键的记录,但存在组合键的错误显示和不能正常使用组合键的问题,例如:CTRL+1 获取到的是CTRL+ ; CTRL+C 获取到的是CTRL+□ ;CTRL+数字键1 获取到的是CTRL+,让Ai代码调整多次未能解决该问题


1.png (48.89 KB, 下载次数: 2)
下载附件
2025-9-8 11:33 上传

问题2:在本软件的热键设置中已设置了可自定义按键及组合, 但是F1 ~F12 不能设置,我通过热键冲突检测提示未有冲突,代码也调整过多次未能解决该问题


2.png (48.8 KB, 下载次数: 2)
下载附件
2025-9-8 11:33 上传



3.png (56.63 KB, 下载次数: 2)
下载附件
2025-9-8 11:33 上传

[Python] 纯文本查看 复制代码import pyautogui
import time
import random
import threading
from pynput import keyboard, mouse
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext, filedialog
import json
import os
import pyperclip
from datetime import datetime
class AutoInputTool:
    def __init__(self, root):
        self.root = root
        self.root.title("辅助工具——By:忆惘惜")
        self.root.geometry("650x750")  # 增加窗口大小以适应内容
        self.root.resizable(True, True)  # 允许调整窗口大小
        
        # 设置字体
        self.font = ("微软雅黑", 9)
        self.title_font = ("微软雅黑", 10, "bold")
        
        # 运行状态控制
        self.text_running = False
        self.key_running = False
        self.mouse_running = False
        self.macro_recording = False
        self.macro_playing = False
        self.text_thread = None
        self.key_thread = None
        self.mouse_thread = None
        self.macro_thread = None
        
        # 热键设置
        self.hotkeys = {
            "text_start": "Ctrl+Shift+1",
            "text_stop": "Ctrl+Shift+Q",
            "key_start": "Ctrl+Shift+2",
            "key_stop": "Ctrl+Shift+W",
            "mouse_start": "Ctrl+Shift+3",
            "mouse_stop": "Ctrl+Shift+E",
            "macro_record": "Ctrl+Shift+R",
            "macro_play": "Ctrl+Shift+T",
            "macro_stop": "Ctrl+Shift+Y"
        }
        
        # 按键记录
        self.recording_key = False
        self.current_key = ""
        self.modifier_keys = []
        
        # 鼠标监听器
        self.mouse_listener = None
        
        # 宏录制
        self.macro_actions = []
        self.macro_start_time = 0
        self.macro_listener = None
        self.macro_mouse_listener = None
        
        # 热键监听器 - 添加这行初始化
        self.listener = None
        
        # 初始化随机种子
        random.seed(time.time())
        
        # 创建界面
        self.create_widgets()
        
        # 加载配置
        self.load_config()
        
        # 启动热键监听
        self.start_hotkey_listener()
        
        # 启动实时坐标更新
        self.update_real_time_coordinates()
        
        # 启动鼠标点击监听
        self.start_mouse_listener()
   
    def create_widgets(self):
        """创建GUI界面组件"""
        style = ttk.Style()
        style.configure("TNotebook", font=self.font)
        style.configure("TNotebook.Tab", font=self.font)
        style.configure("TLabel", font=self.font)
        style.configure("TButton", font=self.font)
        style.configure("TEntry", font=self.font)
        style.configure("TSpinbox", font=self.font)
        style.configure("TCombobox", font=self.font)
        
        # 创建选项卡
        notebook = ttk.Notebook(self.root)
        notebook.pack(fill='both', expand=True, padx=10, pady=10)
        
        # 文本输入选项卡
        text_frame = ttk.Frame(notebook, padding=10)
        notebook.add(text_frame, text='文本输入')
        self.create_text_tab(text_frame)
        
        # 按键操作选项卡
        key_frame = ttk.Frame(notebook, padding=10)
        notebook.add(key_frame, text='按键操作')
        self.create_key_tab(key_frame)
        
        # 坐标捕捉选项卡
        coord_frame = ttk.Frame(notebook, padding=10)
        notebook.add(coord_frame, text='坐标捕捉')
        self.create_coord_tab(coord_frame)
        
        # 鼠标连点选项卡
        mouse_frame = ttk.Frame(notebook, padding=10)
        notebook.add(mouse_frame, text='鼠标连点')
        self.create_mouse_tab(mouse_frame)
        
        # 宏录制选项卡
        macro_frame = ttk.Frame(notebook, padding=10)
        notebook.add(macro_frame, text='宏录制')
        self.create_macro_tab(macro_frame)
        
        # 热键设置选项卡
        hotkey_frame = ttk.Frame(notebook, padding=10)
        notebook.add(hotkey_frame, text='热键设置')
        self.create_hotkey_tab(hotkey_frame)
        
        # 控制按钮
        self.create_control_buttons()
        
        # 状态栏
        self.create_status_bar()
   
    def create_text_tab(self, frame):
        """创建文本输入选项卡"""
        ttk.Label(frame, text="输入文本(支持中文):", font=self.font).grid(row=0, column=0, sticky='w', pady=5)
        self.text_entry = ttk.Entry(frame, width=40, font=self.font)
        self.text_entry.grid(row=0, column=1, pady=5, padx=5, columnspan=2)
        
        ttk.Label(frame, text="间隔时间(毫秒):", font=self.font).grid(row=1, column=0, sticky='w', pady=5)
        self.text_interval = ttk.Entry(frame, width=15, font=self.font)
        self.text_interval.insert(0, "1000")
        self.text_interval.grid(row=1, column=1, sticky='w', pady=5, padx=5)
        
        ttk.Label(frame, text="重复次数(0=无限):", font=self.font).grid(row=2, column=0, sticky='w', pady=5)
        self.text_repeat = ttk.Spinbox(frame, from_=0, to=99999, width=15, font=self.font)
        self.text_repeat.set(10)
        self.text_repeat.grid(row=2, column=1, sticky='w', pady=5, padx=5)
        
        button_frame = ttk.Frame(frame)
        button_frame.grid(row=3, column=0, columnspan=3, pady=10)
        
        self.text_start_button = ttk.Button(button_frame, text="开始", command=self.start_text_input)
        self.text_start_button.pack(side='left', padx=5)
        
        self.text_stop_button = ttk.Button(button_frame, text="结束", command=self.stop_text_input, state='disabled')
        self.text_stop_button.pack(side='left', padx=5)
        
        # 添加快捷键说明
        hotkey_label = ttk.Label(frame, text=f"快捷键: {self.hotkeys['text_start']} 开始, {self.hotkeys['text_stop']} 结束",
                                foreground="blue", font=self.font)
        hotkey_label.grid(row=4, column=0, columnspan=3, pady=5)
        
        note_text = "说明:\n- 支持输入中文、英文、数字和符号\n- 间隔时间:每次喊话之间的等待时间(毫秒)\n- 重复次数:执行次数,0表示无限循环\n- 开始后会自动输入文本并按回车发送"
        note_label = ttk.Label(frame, text=note_text, justify='left', font=self.font)
        note_label.grid(row=5, column=0, columnspan=3, sticky='w', pady=10)
   
    def create_key_tab(self, frame):
        """创建按键操作选项卡 - 改进组合键检测"""
        ttk.Label(frame, text="选择按键:", font=self.font).grid(row=0, column=0, sticky='w', pady=5)
        
        self.key_var = tk.StringVar()
        self.key_var.set("按下任意键...")
        key_label = ttk.Label(frame, textvariable=self.key_var, foreground="blue", font=self.font)
        key_label.grid(row=0, column=1, sticky='w', pady=5, padx=5)
        
        self.detect_key_button = ttk.Button(frame, text="开始检测按键", command=self.start_key_detection)
        self.detect_key_button.grid(row=1, column=0, pady=5, padx=5)
        
        ttk.Label(frame, text="组合键说明:", font=self.font).grid(row=2, column=0, sticky='w', pady=5)
        combo_note = ttk.Label(frame, text="按住Ctrl/Shift/Alt再按其他键可记录组合键", foreground="green", font=self.font)
        combo_note.grid(row=2, column=1, sticky='w', pady=5, padx=5)
        
        ttk.Label(frame, text="间隔时间(毫秒):", font=self.font).grid(row=3, column=0, sticky='w', pady=5)
        self.key_interval = ttk.Entry(frame, width=15, font=self.font)
        self.key_interval.insert(0, "1000")
        self.key_interval.grid(row=3, column=1, sticky='w', pady=5, padx=5)
        
        ttk.Label(frame, text="重复次数(0=无限):", font=self.font).grid(row=4, column=0, sticky='w', pady=5)
        self.key_repeat = ttk.Spinbox(frame, from_=0, to=99999, width=15, font=self.font)
        self.key_repeat.set(10)
        self.key_repeat.grid(row=4, column=1, sticky='w', pady=5, padx=5)
        
        button_frame = ttk.Frame(frame)
        button_frame.grid(row=5, column=0, columnspan=3, pady=10)
        
        self.key_start_button = ttk.Button(button_frame, text="开始", command=self.start_key_input)
        self.key_start_button.pack(side='left', padx=5)
        
        self.key_stop_button = ttk.Button(button_frame, text="结束", command=self.stop_key_input, state='disabled')
        self.key_stop_button.pack(side='left', padx=5)
        
        # 添加快捷键说明
        hotkey_label = ttk.Label(frame, text=f"快捷键: {self.hotkeys['key_start']} 开始, {self.hotkeys['key_stop']} 结束",
                                foreground="blue", font=self.font)
        hotkey_label.grid(row=6, column=0, columnspan=3, pady=5)
        
        note_text = "说明:\n- 点击'开始检测按键'后按下键盘任意键\n- 支持组合键:按住Ctrl/Shift/Alt再按其他键\n- 支持功能键与字母键组合:Ctrl+1, Ctrl+Alt+C等\n- 间隔时间:每次按键之间的等待时间(毫秒)\n- 重复次数:执行次数,0表示无限循环"
        note_label = ttk.Label(frame, text=note_text, justify='left', font=self.font)
        note_label.grid(row=7, column=0, columnspan=3, sticky='w', pady=10)
   
    def create_coord_tab(self, frame):
        """创建坐标捕捉选项卡"""
        coord_frame = ttk.LabelFrame(frame, text="实时鼠标位置", padding=5)
        coord_frame.grid(row=0, column=0, columnspan=2, sticky='ew', pady=10)
        
        self.real_time_coord = tk.StringVar()
        self.real_time_coord.set("X: 0, Y: 0")
        coord_label = ttk.Label(coord_frame, textvariable=self.real_time_coord, font=("微软雅黑", 10, "bold"))
        coord_label.pack()
        
        ttk.Label(frame, text="目标X坐标:", font=self.font).grid(row=1, column=0, sticky='w', pady=5)
        self.x_entry = ttk.Entry(frame, width=10, font=self.font)
        self.x_entry.grid(row=1, column=1, sticky='w', pady=5, padx=5)
        
        ttk.Label(frame, text="目标Y坐标:", font=self.font).grid(row=2, column=0, sticky='w', pady=5)
        self.y_entry = ttk.Entry(frame, width=10, font=self.font)
        self.y_entry.grid(row=2, column=1, sticky='w', pady=5, padx=5)
        
        self.record_status = tk.StringVar()
        self.record_status.set("点击记录: 启用中")
        status_label = ttk.Label(frame, textvariable=self.record_status, foreground="green", font=self.font)
        status_label.grid(row=3, column=0, columnspan=2, pady=5)
        
        note_text = "说明:\n- 实时位置:自动显示当前鼠标坐标\n- 点击左键自动记录坐标到输入框\n- 目标坐标:设置鼠标点击的目标位置\n- 坐标记录功能始终启用"
        note_label = ttk.Label(frame, text=note_text, justify='left', font=self.font)
        note_label.grid(row=4, column=0, columnspan=2, sticky='w', pady=10)
   
    def create_mouse_tab(self, frame):
        """创建鼠标连点选项卡 - 简化版"""
        ttk.Label(frame, text="点击类型:", font=self.font).grid(row=0, column=0, sticky='w', pady=5)
        self.click_type = ttk.Combobox(frame, values=["左键", "右键", "中键"], width=8, state="readonly", font=self.font)
        self.click_type.current(0)
        self.click_type.grid(row=0, column=1, sticky='w', pady=5, padx=5)
        
        ttk.Label(frame, text="点击次数:", font=self.font).grid(row=1, column=0, sticky='w', pady=5)
        self.click_count = ttk.Entry(frame, width=10, font=self.font)
        self.click_count.insert(0, "1")
        self.click_count.grid(row=1, column=1, sticky='w', pady=5, padx=5)
        
        ttk.Label(frame, text="间隔时间(毫秒):", font=self.font).grid(row=2, column=0, sticky='w', pady=5)
        self.mouse_interval = ttk.Entry(frame, width=10, font=self.font)
        self.mouse_interval.insert(0, "1000")
        self.mouse_interval.grid(row=2, column=1, sticky='w', pady=5, padx=5)
        
        button_frame = ttk.Frame(frame)
        button_frame.grid(row=3, column=0, columnspan=2, pady=10)
        
        self.mouse_start_button = ttk.Button(button_frame, text="开始", command=self.start_mouse_input)
        self.mouse_start_button.pack(side='left', padx=5)
        
        self.mouse_stop_button = ttk.Button(button_frame, text="结束", command=self.stop_mouse_input, state='disabled')
        self.mouse_stop_button.pack(side='left', padx=5)
        
        # 添加快捷键说明
        hotkey_label = ttk.Label(frame, text=f"快捷键: {self.hotkeys['mouse_start']} 开始, {self.hotkeys['mouse_stop']} 结束",
                                foreground="blue", font=self.font)
        hotkey_label.grid(row=4, column=0, columnspan=2, pady=5)
        
        note_text = "说明:\n- 在当前鼠标位置进行连点操作\n- 点击类型:选择鼠标按键类型\n- 点击次数:每次循环的点击次数\n- 间隔时间:每次点击的间隔时间(毫秒)"
        note_label = ttk.Label(frame, text=note_text, justify='left', font=self.font)
        note_label.grid(row=5, column=0, columnspan=2, sticky='w', pady=10)
   
    def create_macro_tab(self, frame):
        """创建宏录制选项卡 - 改进版"""
        # 宏设置区域
        settings_frame = ttk.LabelFrame(frame, text="宏设置", padding=5)
        settings_frame.grid(row=0, column=0, columnspan=2, sticky='ew', pady=10)
        
        ttk.Label(settings_frame, text="播放间隔(毫秒):", font=self.font).grid(row=0, column=0, sticky='w', pady=5)
        self.macro_interval = ttk.Entry(settings_frame, width=10, font=self.font)
        self.macro_interval.insert(0, "100")
        self.macro_interval.grid(row=0, column=1, sticky='w', pady=5, padx=5)
        
        ttk.Label(settings_frame, text="重复次数:", font=self.font).grid(row=0, column=2, sticky='w', pady=5, padx=(20, 5))
        self.macro_repeat = ttk.Spinbox(settings_frame, from_=1, to=999, width=8, font=self.font)
        self.macro_repeat.set(1)
        self.macro_repeat.grid(row=0, column=3, sticky='w', pady=5, padx=5)
        
        # 录制控制按钮
        button_frame = ttk.Frame(frame)
        button_frame.grid(row=1, column=0, columnspan=2, pady=10, sticky='ew')
        
        self.macro_record_button = ttk.Button(button_frame, text="开始录制", command=self.toggle_macro_recording)
        self.macro_record_button.pack(side='left', padx=5)
        
        self.macro_play_button = ttk.Button(button_frame, text="开始播放", command=self.play_macro, state='disabled')
        self.macro_play_button.pack(side='left', padx=5)
        
        self.macro_stop_button = ttk.Button(button_frame, text="结束播放", command=self.stop_macro_playback, state='disabled')
        self.macro_stop_button.pack(side='left', padx=5)
        
        self.macro_clear_button = ttk.Button(button_frame, text="清空宏", command=self.clear_macro)
        self.macro_clear_button.pack(side='left', padx=5)
        
        # 添加快捷键说明
        hotkey_frame = ttk.Frame(frame)
        hotkey_frame.grid(row=2, column=0, columnspan=2, pady=5)
        
        hotkey_label = ttk.Label(hotkey_frame,
                                text=f"快捷键: {self.hotkeys['macro_record']} 录制, {self.hotkeys['macro_play']} 播放, {self.hotkeys['macro_stop']} 停止",
                                foreground="blue", font=self.font)
        hotkey_label.pack()
        
        # 宏记录显示
        record_frame = ttk.LabelFrame(frame, text="宏记录", padding=5)
        record_frame.grid(row=3, column=0, columnspan=2, pady=10, sticky='nsew')
        frame.rowconfigure(3, weight=1)
        frame.columnconfigure(0, weight=1)
        frame.columnconfigure(1, weight=1)
        
        # 使用Treeview
        columns = ("时间", "类型", "详情")
        self.macro_tree = ttk.Treeview(record_frame, columns=columns, show="headings", height=8)
        
        # 设置列宽和标题
        self.macro_tree.heading("时间", text="时间 (ms)")
        self.macro_tree.heading("类型", text="类型")
        self.macro_tree.heading("详情", text="详情")
        
        self.macro_tree.column("时间", width=80, anchor='center')
        self.macro_tree.column("类型", width=100, anchor='center')
        self.macro_tree.column("详情", width=200, anchor='w')
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(record_frame, orient="vertical", command=self.macro_tree.yview)
        self.macro_tree.configure(yscrollcommand=scrollbar.set)
        
        self.macro_tree.pack(side='left', fill='both', expand=True)
        scrollbar.pack(side='right', fill='y')
        
        # 宏编辑和保存
        edit_frame = ttk.Frame(frame)
        edit_frame.grid(row=4, column=0, columnspan=2, pady=10, sticky='ew')
        
        ttk.Button(edit_frame, text="保存宏", command=self.save_macro).pack(side='left', padx=5)
        ttk.Button(edit_frame, text="加载宏", command=self.load_macro).pack(side='left', padx=5)
        ttk.Button(edit_frame, text="删除选中", command=self.delete_selected_macro).pack(side='left', padx=5)
        
        note_text = "说明:\n- 开始录制宏:记录所有鼠标和键盘操作\n- 播放宏:执行录制的操作序列\n- 播放间隔:每个动作之间的额外延迟时间\n- 重复次数:宏播放的执行次数"
        note_label = ttk.Label(frame, text=note_text, justify='left', font=self.font)
        note_label.grid(row=5, column=0, columnspan=2, sticky='w', pady=10)
   
    def create_hotkey_tab(self, frame):
        """创建热键设置选项卡 - 改为自定义输入"""
        # 文本输入热键
        ttk.Label(frame, text="文本输入开始热键:", font=self.font).grid(row=0, column=0, sticky='w', pady=5)
        self.text_start_hotkey_var = tk.StringVar(value=self.hotkeys["text_start"])
        self.text_start_hotkey_entry = ttk.Entry(frame, textvariable=self.text_start_hotkey_var, width=15, font=self.font)
        self.text_start_hotkey_entry.grid(row=0, column=1, sticky='w', pady=5, padx=5)
        
        ttk.Label(frame, text="文本输入结束热键:", font=self.font).grid(row=0, column=2, sticky='w', pady=5, padx=(20, 5))
        self.text_stop_hotkey_var = tk.StringVar(value=self.hotkeys["text_stop"])
        self.text_stop_hotkey_entry = ttk.Entry(frame, textvariable=self.text_stop_hotkey_var, width=15, font=self.font)
        self.text_stop_hotkey_entry.grid(row=0, column=3, sticky='w', pady=5, padx=5)
        
        # 按键操作热键
        ttk.Label(frame, text="按键操作开始热键:", font=self.font).grid(row=1, column=0, sticky='w', pady=5)
        self.key_start_hotkey_var = tk.StringVar(value=self.hotkeys["key_start"])
        self.key_start_hotkey_entry = ttk.Entry(frame, textvariable=self.key_start_hotkey_var, width=15, font=self.font)
        self.key_start_hotkey_entry.grid(row=1, column=1, sticky='w', pady=5, padx=5)
        
        ttk.Label(frame, text="按键操作结束热键:", font=self.font).grid(row=1, column=2, sticky='w', pady=5, padx=(20, 5))
        self.key_stop_hotkey_var = tk.StringVar(value=self.hotkeys["key_stop"])
        self.key_stop_hotkey_entry = ttk.Entry(frame, textvariable=self.key_stop_hotkey_var, width=15, font=self.font)
        self.key_stop_hotkey_entry.grid(row=1, column=3, sticky='w', pady=5, padx=5)
        
        # 鼠标连点热键
        ttk.Label(frame, text="鼠标连点开始热键:", font=self.font).grid(row=2, column=0, sticky='w', pady=5)
        self.mouse_start_hotkey_var = tk.StringVar(value=self.hotkeys["mouse_start"])
        self.mouse_start_hotkey_entry = ttk.Entry(frame, textvariable=self.mouse_start_hotkey_var, width=15, font=self.font)
        self.mouse_start_hotkey_entry.grid(row=2, column=1, sticky='w', pady=5, padx=5)
        
        ttk.Label(frame, text="鼠标连点结束热键:", font=self.font).grid(row=2, column=2, sticky='w', pady=5, padx=(20, 5))
        self.mouse_stop_hotkey_var = tk.StringVar(value=self.hotkeys["mouse_stop"])
        self.mouse_stop_hotkey_entry = ttk.Entry(frame, textvariable=self.mouse_stop_hotkey_var, width=15, font=self.font)
        self.mouse_stop_hotkey_entry.grid(row=2, column=3, sticky='w', pady=5, padx=5)
        
        # 宏操作热键
        ttk.Label(frame, text="宏录制热键:", font=self.font).grid(row=3, column=0, sticky='w', pady=5)
        self.macro_record_hotkey_var = tk.StringVar(value=self.hotkeys["macro_record"])
        self.macro_record_hotkey_entry = ttk.Entry(frame, textvariable=self.macro_record_hotkey_var, width=15, font=self.font)
        self.macro_record_hotkey_entry.grid(row=3, column=1, sticky='w', pady=5, padx=5)
        
        ttk.Label(frame, text="宏播放热键:", font=self.font).grid(row=3, column=2, sticky='w', pady=5, padx=(20, 5))
        self.macro_play_hotkey_var = tk.StringVar(value=self.hotkeys["macro_play"])
        self.macro_play_hotkey_entry = ttk.Entry(frame, textvariable=self.macro_play_hotkey_var, width=15, font=self.font)
        self.macro_play_hotkey_entry.grid(row=3, column=3, sticky='w', pady=5, padx=5)
        
        ttk.Label(frame, text="宏停止热键:", font=self.font).grid(row=4, column=0, sticky='w', pady=5)
        self.macro_stop_hotkey_var = tk.StringVar(value=self.hotkeys["macro_stop"])
        self.macro_stop_hotkey_entry = ttk.Entry(frame, textvariable=self.macro_stop_hotkey_var, width=15, font=self.font)
        self.macro_stop_hotkey_entry.grid(row=4, column=1, sticky='w', pady=5, padx=5)
        
        # 热键检测按钮
        detect_button = ttk.Button(frame, text="检测热键冲突", command=self.check_hotkey_conflicts)
        detect_button.grid(row=5, column=0, columnspan=2, pady=10)
        
        # 应用按钮
        apply_button = ttk.Button(frame, text="应用热键设置", command=self.apply_hotkey_settings)
        apply_button.grid(row=5, column=2, columnspan=2, pady=10)
        
        note_text = "说明:\n- 输入格式: 修饰键+键名 (如: Ctrl+Shift+1, F11, F12)\n- 支持修饰键: Ctrl, Shift, Alt\n- 支持功能键: F1-F12\n- 点击'检测热键冲突'检查是否有重复热键\n- 点击'应用热键设置'使更改生效"
        note_label = ttk.Label(frame, text=note_text, justify='left', font=self.font)
        note_label.grid(row=6, column=0, columnspan=4, sticky='w', pady=10)
   
    def create_control_buttons(self):
        """创建控制按钮"""
        button_frame = ttk.Frame(self.root)
        button_frame.pack(fill='x', pady=10)
        
        ttk.Button(button_frame, text="保存配置", command=self.save_config).pack(side='left', padx=20)
        ttk.Button(button_frame, text="退出", command=self.exit_app).pack(side='left', padx=20)
   
    def create_status_bar(self):
        """创建状态栏"""
        self.status_var = tk.StringVar(value="就绪 - 实时坐标显示已启用")
        status_bar = ttk.Label(self.root, textvariable=self.status_var, relief='sunken', font=self.font)
        status_bar.pack(side='bottom', fill='x')
   
    def update_real_time_coordinates(self):
        """实时更新鼠标坐标显示"""
        if hasattr(self, 'real_time_coord'):
            try:
                x, y = pyautogui.position()
                self.real_time_coord.set(f"X: {x}, Y: {y}")
            except Exception as e:
                self.real_time_coord.set("无法获取坐标")
            
            self.root.after(100, self.update_real_time_coordinates)
   
    def start_mouse_listener(self):
        """启动鼠标点击监听器"""
        def on_click(x, y, button, pressed):
            if pressed and button == mouse.Button.left:
                self.x_entry.delete(0, tk.END)
                self.x_entry.insert(0, str(x))
                self.y_entry.delete(0, tk.END)
                self.y_entry.insert(0, str(y))
                self.status_var.set(f"已记录点击位置: ({x}, {y})")
        
        self.mouse_listener = mouse.Listener(on_click=on_click)
        self.mouse_listener.daemon = True
        self.mouse_listener.start()
   
    def start_key_detection(self):
        """开始检测按键 - 改进组合键检测"""
        self.recording_key = True
        self.key_var.set("按下任意键...")
        self.modifier_keys = []
        self.status_var.set("按键检测中,请按下键盘上的任意键...")
        self.detect_key_button.config(state='disabled')
        
        def on_press(key):
            if self.recording_key:
                try:
                    # 获取按键名称
                    key_name = self.get_key_name(key)
                    
                    # 处理功能键
                    if key_name in ['ctrl', 'shift', 'alt', 'ctrl_r', 'shift_r', 'alt_r', 'ctrl_l', 'shift_l', 'alt_l']:
                        base_name = key_name.replace('_r', '').replace('_l', '')
                        if base_name not in self.modifier_keys:
                            self.modifier_keys.append(base_name)
                        return True  # 继续监听
                    
                    # 组合键处理
                    if self.modifier_keys:
                        key_name = '+'.join(self.modifier_keys) + '+' + key_name
                    
                    self.current_key = key_name
                    self.key_var.set(f"已选择: {key_name}")
                    self.recording_key = False
                    self.detect_key_button.config(state='normal')
                    self.status_var.set(f"已选择按键: {key_name}")
                    return False  # 停止监听
                    
                except Exception as e:
                    self.status_var.set(f"按键检测错误: {str(e)}")
                    self.recording_key = False
                    self.detect_key_button.config(state='normal')
                    return False
        
        listener = keyboard.Listener(on_press=on_press)
        listener.daemon = True
        listener.start()
   
    def get_key_name(self, key):
        """将按键转换为可读的名称"""
        try:
            # 处理特殊键
            if hasattr(key, 'name'):
                # 处理小键盘数字键
                if hasattr(key, 'vk') and 96 ').replace('shift', '').replace('alt', '')
                if key == "text_start":
                    hotkey_map[converted] = self.start_text_input
                elif key == "text_stop":
                    hotkey_map[converted] = self.stop_text_input
                elif key == "key_start":
                    hotkey_map[converted] = self.start_key_input
                elif key == "key_stop":
                    hotkey_map[converted] = self.stop_key_input
                elif key == "mouse_start":
                    hotkey_map[converted] = self.start_mouse_input
                elif key == "mouse_stop":
                    hotkey_map[converted] = self.stop_mouse_input
                elif key == "macro_record":
                    hotkey_map[converted] = self.toggle_macro_recording
                elif key == "macro_play":
                    hotkey_map[converted] = self.play_macro
                elif key == "macro_stop":
                    hotkey_map[converted] = self.stop_macro_playback
            
            self.listener = keyboard.GlobalHotKeys(hotkey_map)
            self.listener.start()
            self.status_var.set(f"热键监听已启动")
        except Exception as e:
            self.status_var.set(f"热键设置错误: {str(e)}")
   
    def check_hotkey_conflicts(self):
        """检查热键冲突"""
        hotkey_values = list(self.hotkeys.values())
        conflicts = []
        
        # 检查重复的热键
        for i, hotkey1 in enumerate(hotkey_values):
            for j, hotkey2 in enumerate(hotkey_values):
                if i != j and hotkey1.lower() == hotkey2.lower():
                    conflict = f"{list(self.hotkeys.keys())} 和 {list(self.hotkeys.keys())[j]} 都使用了 {hotkey1}"
                    if conflict not in conflicts:
                        conflicts.append(conflict)
        
        if conflicts:
            messagebox.showwarning("热键冲突", "发现以下热键冲突:\n\n" + "\n".join(conflicts))
        else:
            messagebox.showinfo("热键检查", "未发现热键冲突")
   
    def apply_hotkey_settings(self):
        """应用热键设置"""
        new_hotkeys = {
            "text_start": self.text_start_hotkey_var.get(),
            "text_stop": self.text_stop_hotkey_var.get(),
            "key_start": self.key_start_hotkey_var.get(),
            "key_stop": self.key_stop_hotkey_var.get(),
            "mouse_start": self.mouse_start_hotkey_var.get(),
            "mouse_stop": self.mouse_stop_hotkey_var.get(),
            "macro_record": self.macro_record_hotkey_var.get(),
            "macro_play": self.macro_play_hotkey_var.get(),
            "macro_stop": self.macro_stop_hotkey_var.get()
        }
        
        # 检查是否有空值
        for name, value in new_hotkeys.items():
            if not value.strip():
                messagebox.showerror("错误", f"{name} 的热键不能为空")
                return
        
        # 检查热键冲突
        hotkey_values = list(new_hotkeys.values())
        for i, hotkey1 in enumerate(hotkey_values):
            for j, hotkey2 in enumerate(hotkey_values):
                if i != j and hotkey1.lower() == hotkey2.lower():
                    messagebox.showerror("热键冲突", f"发现热键冲突: {hotkey1} 被多次使用")
                    return
        
        # 应用新热键
        self.hotkeys = new_hotkeys
        
        # 更新界面上的快捷键说明
        self.update_hotkey_labels()
        
        # 重新启动热键监听
        self.start_hotkey_listener()
        
        self.status_var.set("热键设置已应用")
        messagebox.showinfo("成功", "热键设置已成功应用")
   
    def update_hotkey_labels(self):
        """更新界面上的快捷键说明"""
        # 文本输入选项卡
        for widget in self.root.winfo_children():
            if isinstance(widget, ttk.Notebook):
                for tab_id in widget.tabs():
                    tab = widget.nametowidget(tab_id)
                    if "文本输入" in widget.tab(tab_id, "text"):
                        for child in tab.winfo_children():
                            if isinstance(child, ttk.Label) and "快捷键:" in child.cget("text"):
                                child.config(text=f"快捷键: {self.hotkeys['text_start']} 开始, {self.hotkeys['text_stop']} 结束")
                    elif "按键操作" in widget.tab(tab_id, "text"):
                        for child in tab.winfo_children():
                            if isinstance(child, ttk.Label) and "快捷键:" in child.cget("text"):
                                child.config(text=f"快捷键: {self.hotkeys['key_start']} 开始, {self.hotkeys['key_stop']} 结束")
                    elif "鼠标连点" in widget.tab(tab_id, "text"):
                        for child in tab.winfo_children():
                            if isinstance(child, ttk.Label) and "快捷键:" in child.cget("text"):
                                child.config(text=f"快捷键: {self.hotkeys['mouse_start']} 开始, {self.hotkeys['mouse_stop']} 结束")
                    elif "宏录制" in widget.tab(tab_id, "text"):
                        for child in tab.winfo_children():
                            if isinstance(child, ttk.Label) and "快捷键:" in child.cget("text"):
                                child.config(text=f"快捷键: {self.hotkeys['macro_record']} 录制, {self.hotkeys['macro_play']} 播放, {self.hotkeys['macro_stop']} 停止")
   
    def perform_text_input(self):
        """执行文本输入操作 - 支持中文"""
        try:
            text = self.text_entry.get()
            base_interval = float(self.text_interval.get())
            repeat_count = int(self.text_repeat.get())
            
            if not text:
                self.status_var.set("请输入文本内容")
                return
            
            if repeat_count == 0:
                repeat_count = 999999
            
            self.status_var.set("文本输入运行中...")
            
            for i in range(repeat_count):
                if not self.text_running:
                    break
               
                time.sleep(0.5)
               
                # 使用剪贴板支持中文输入
                pyperclip.copy(text)
                time.sleep(0.1)
               
                # 模拟粘贴操作
                pyautogui.hotkey('ctrl', 'v')
               
                # 按回车发送
                pyautogui.press('enter')
               
                if repeat_count == 999999:
                    self.status_var.set(f"已发送: {text} (无限循环)")
                else:
                    self.status_var.set(f"已发送: {text} ({i+1}/{repeat_count})")
               
                delay = base_interval / 1000
                time.sleep(delay)
               
        except Exception as e:
            self.status_var.set(f"文本输入错误: {str(e)}")
        finally:
            self.stop_text_input()
   
    def perform_key_input(self):
        """执行按键操作 - 支持组合键"""
        try:
            key = self.current_key
            base_interval = float(self.key_interval.get())
            repeat_count = int(self.key_repeat.get())
            
            if not key:
                self.status_var.set("请先选择按键")
                return
            
            if repeat_count == 0:
                repeat_count = 999999
            
            self.status_var.set("按键操作运行中...")
            
            for i in range(repeat_count):
                if not self.key_running:
                    break
               
                time.sleep(0.5)
               
                # 执行按键操作(支持组合键)
                if '+' in key:
                    # 处理组合键
                    keys = key.split('+')
                    pyautogui.hotkey(*keys)
                else:
                    # 单键
                    pyautogui.press(key)
               
                if repeat_count == 999999:
                    self.status_var.set(f"已按下按键: {key} (无限循环)")
                else:
                    self.status_var.set(f"已按下按键: {key} ({i+1}/{repeat_count})")
                delay = base_interval / 1000
                time.sleep(delay)
        except Exception as e:
            self.status_var.set(f"按键操作错误: {str(e)}")
        finally:
            self.stop_key_input()
    def perform_mouse_input(self):
        """执行鼠标操作 - 简化版:在当前位置连点"""
        try:
            click_type = self.click_type.get()
            click_count = int(self.click_count.get())
            base_interval = float(self.mouse_interval.get()) / 1000
            button_map = {"左键": "left", "右键": "right", "中键": "middle"}
            button = button_map[click_type]
            self.status_var.set("鼠标连点运行中...")
            for i in range(click_count):
                if not self.mouse_running:
                    break
                # 在当前鼠标位置点击
                pyautogui.click(button=button)
                self.status_var.set(f"已点击: {click_type} ({i + 1}/{click_count})")
                delay = base_interval
                time.sleep(delay)
        except Exception as e:
            self.status_var.set(f"鼠标操作错误: {str(e)}")
        finally:
            self.stop_mouse_input()
    def human_move_to(self, x, y, duration=0.5):
        """人类化鼠标移动"""
        pyautogui.moveTo(x, y, duration=duration)
    def start_text_input(self):
        """开始文本输入"""
        self.text_running = True
        self.text_start_button.config(state='disabled')
        self.text_stop_button.config(state='normal')
        self.text_thread = threading.Thread(target=self.perform_text_input)
        self.text_thread.daemon = True
        self.text_thread.start()
    def stop_text_input(self):
        """停止文本输入"""
        self.text_running = False
        self.text_start_button.config(state='normal')
        self.text_stop_button.config(state='disabled')
        self.status_var.set("文本输入已停止")
    def start_key_input(self):
        """开始按键输入"""
        if not self.current_key:
            self.status_var.set("请先选择按键")
            return
        self.key_running = True
        self.key_start_button.config(state='disabled')
        self.key_stop_button.config(state='normal')
        self.key_thread = threading.Thread(target=self.perform_key_input)
        self.key_thread.daemon = True
        self.key_thread.start()
    def stop_key_input(self):
        """停止按键输入"""
        self.key_running = False
        self.key_start_button.config(state='normal')
        self.key_stop_button.config(state='disabled')
        self.status_var.set("按键输入已停止")
    def start_mouse_input(self):
        """开始鼠标输入"""
        self.mouse_running = True
        self.mouse_start_button.config(state='disabled')
        self.mouse_stop_button.config(state='normal')
        self.mouse_thread = threading.Thread(target=self.perform_mouse_input)
        self.mouse_thread.daemon = True
        self.mouse_thread.start()
    def stop_mouse_input(self):
        """停止鼠标输入"""
        self.mouse_running = False
        self.mouse_start_button.config(state='normal')
        self.mouse_stop_button.config(state='disabled')
        self.status_var.set("鼠标输入已停止")
    def toggle_macro_recording(self):
        """切换宏录制状态"""
        if not self.macro_recording:
            self.start_macro_recording()
        else:
            self.stop_macro_recording()
   
    def start_macro_recording(self):
        """开始宏录制 - 修复小键盘数字键问题"""
        self.macro_recording = True
        self.macro_actions = []
        self.macro_start_time = time.time()
        self.macro_record_button.config(text="停止录制")
        self.macro_play_button.config(state='disabled')
        self.status_var.set("宏录制中...")
        
        # 启动键盘监听
        def on_press(key):
            if self.macro_recording:
                try:
                    key_name = self.get_key_name(key)
                    
                    # 处理功能键
                    if key_name in ['ctrl', 'shift', 'alt', 'ctrl_r', 'shift_r', 'alt_r', 'ctrl_l', 'shift_l', 'alt_l']:
                        base_name = key_name.replace('_r', '').replace('_l', '')
                        if base_name not in self.modifier_keys:
                            self.modifier_keys.append(base_name)
                        return True  # 继续监听
                    
                    # 组合键处理
                    if self.modifier_keys:
                        key_name = '+'.join(self.modifier_keys) + '+' + key_name
                        self.modifier_keys = []  # 重置修饰键
                    
                    action = {
                        "type": "key_press",
                        "key": key_name,
                        "time": round((time.time() - self.macro_start_time) * 1000)  # 毫秒
                    }
                    self.macro_actions.append(action)
                    self.update_macro_display()
                    
                except Exception as e:
                    self.status_var.set(f"录制错误: {str(e)}")
        
        self.macro_listener = keyboard.Listener(on_press=on_press)
        self.macro_listener.daemon = True
        self.macro_listener.start()
        
        # 启动鼠标监听
        def on_click(x, y, button, pressed):
            if self.macro_recording and pressed:
                action = {
                    "type": "mouse_click",
                    "button": str(button).replace("Button.", ""),
                    "x": x,
                    "y": y,
                    "time": round((time.time() - self.macro_start_time) * 1000)  # 毫秒
                }
                self.macro_actions.append(action)
                self.update_macro_display()
        
        self.macro_mouse_listener = mouse.Listener(on_click=on_click)
        self.macro_mouse_listener.daemon = True
        self.macro_mouse_listener.start()
   
    def stop_macro_recording(self):
        """停止宏录制"""
        self.macro_recording = False
        self.macro_record_button.config(text="开始录制")
        self.macro_play_button.config(state='normal')
        self.status_var.set("宏录制已停止")
        
        if self.macro_listener:
            self.macro_listener.stop()
        if self.macro_mouse_listener:
            self.macro_mouse_listener.stop()
   
    def update_macro_display(self):
        """更新宏记录显示"""
        # 清空Treeview
        for item in self.macro_tree.get_children():
            self.macro_tree.delete(item)
        
        # 添加新数据
        for i, action in enumerate(self.macro_actions):
            time_ms = action['time']
            
            if action['type'] == 'key_press':
                self.macro_tree.insert("", "end", values=(time_ms, "按键", action['key']))
            elif action['type'] == 'mouse_click':
                self.macro_tree.insert("", "end", values=(time_ms, "鼠标点击", f"{action['button']} at ({action['x']}, {action['y']})"))
   
    def delete_selected_macro(self):
        """删除选中的宏动作"""
        selected = self.macro_tree.selection()
        if selected:
            # 获取选中项的索引
            indices = [self.macro_tree.index(item) for item in selected]
            # 从后往前删除,避免索引变化
            for index in sorted(indices, reverse=True):
                if index  0:
                        time.sleep(wait_time)
                    
                    # 添加额外间隔
                    if extra_interval > 0 and i > 0:
                        time.sleep(extra_interval)
                    
                    # 执行动作
                    if action['type'] == 'key_press':
                        if '+' in action['key']:
                            keys = action['key'].split('+')
                            pyautogui.hotkey(*keys)
                        else:
                            pyautogui.press(action['key'])
                    elif action['type'] == 'mouse_click':
                        button_map = {"left": "left", "right": "right", "middle": "middle"}
                        button = button_map.get(action['button'].lower(), "left")
                        pyautogui.click(action['x'], action['y'], button=button)
                    
                    last_action_time = action['time']
               
                if not self.macro_playing:
                    break
            
        except Exception as e:
            self.status_var.set(f"宏播放错误: {str(e)}")
        finally:
            self.stop_macro_playback()
   
    def stop_macro_playback(self):
        """停止宏播放"""
        self.macro_playing = False
        self.macro_play_button.config(state='normal')
        self.macro_stop_button.config(state='disabled')
        self.macro_record_button.config(state='normal')
        self.status_var.set("宏播放已停止")
   
    def clear_macro(self):
        """清空宏记录"""
        self.macro_actions = []
        for item in self.macro_tree.get_children():
            self.macro_tree.delete(item)
        self.status_var.set("宏记录已清空")
   
    def save_macro(self):
        """保存宏到文件"""
        if not self.macro_actions:
            messagebox.showerror("错误", "没有可保存的宏记录")
            return
        
        file_path = filedialog.asksaveasfilename(
            defaultextension=".json",
            filetypes=[("JSON files", "*.json"), ("All files", "*.*")]
        )
        
        if file_path:
            try:
                with open(file_path, 'w') as f:
                    json.dump({
                        "actions": self.macro_actions,
                        "interval": self.macro_interval.get(),
                        "repeat": self.macro_repeat.get(),
                        "saved_at": datetime.now().isoformat()
                    }, f, indent=2)
                self.status_var.set(f"宏已保存到: {file_path}")
            except Exception as e:
                messagebox.showerror("错误", f"保存宏失败: {str(e)}")
   
    def load_macro(self):
        """从文件加载宏"""
        file_path = filedialog.askopenfilename(
            filetypes=[("JSON files", "*.json"), ("All files", "*.*")]
        )
        
        if file_path:
            try:
                with open(file_path, 'r') as f:
                    data = json.load(f)
                    self.macro_actions = data.get("actions", [])
                    self.macro_interval.delete(0, tk.END)
                    self.macro_interval.insert(0, str(data.get("interval", 100)))
                    self.macro_repeat.set(data.get("repeat", 1))
               
                self.update_macro_display()
                self.status_var.set(f"宏已从 {file_path} 加载")
            except Exception as e:
                messagebox.showerror("错误", f"加载宏失败: {str(e)}")
    def exit_app(self):
        """退出应用程序"""
        self.text_running = False
        self.key_running = False
        self.mouse_running = False
        self.macro_recording = False
        self.macro_playing = False
        if self.listener:
            self.listener.stop()
        if self.mouse_listener:
            self.mouse_listener.stop()
        if self.macro_listener:
            self.macro_listener.stop()
        if self.macro_mouse_listener:
            self.macro_mouse_listener.stop()
        self.root.destroy()
    def save_config(self):
        """保存配置到文件"""
        config = {
            "text": {
                "content": self.text_entry.get(),
                "interval": self.text_interval.get(),
                "repeat": self.text_repeat.get()
            },
            "key": {
                "selected": self.current_key,
                "interval": self.key_interval.get(),
                "repeat": self.key_repeat.get()
            },
            "mouse": {
                "click_type": self.click_type.get(),
                "click_count": self.click_count.get(),
                "interval": self.mouse_interval.get()
            },
            "macro": {
                "interval": self.macro_interval.get(),
                "repeat": self.macro_repeat.get()
            },
            "hotkeys": self.hotkeys
        }
        with open("auto_input_config.json", "w") as f:
            json.dump(config, f, indent=4)
        self.status_var.set("配置已保存")
    def load_config(self):
        """从文件加载配置"""
        if not os.path.exists("auto_input_config.json"):
            return
        try:
            with open("auto_input_config.json", "r") as f:
                config = json.load(f)
            # 文本配置
            if "text" in config:
                text_cfg = config["text"]
                self.text_entry.delete(0, tk.END)
                self.text_entry.insert(0, text_cfg.get("content", ""))
                self.text_interval.delete(0, tk.END)
                self.text_interval.insert(0, text_cfg.get("interval", "1000"))
                self.text_repeat.set(text_cfg.get("repeat", "10"))
            # 按键配置
            if "key" in config:
                key_cfg = config["key"]
                self.current_key = key_cfg.get("selected", "")
                self.key_var.set(f"已选择: {self.current_key}" if self.current_key else "按下任意键...")
                self.key_interval.delete(0, tk.END)
                self.key_interval.insert(0, key_cfg.get("interval", "1000"))
                self.key_repeat.set(key_cfg.get("repeat", "10"))
            # 鼠标配置
            if "mouse" in config:
                m = config["mouse"]
                self.click_type.set(m.get("click_type", "左键"))
                self.click_count.delete(0, tk.END)
                self.click_count.insert(0, m.get("click_count", "1"))
                self.mouse_interval.delete(0, tk.END)
                self.mouse_interval.insert(0, m.get("interval", "1000"))
            # 宏配置
            if "macro" in config:
                macro_cfg = config["macro"]
                self.macro_interval.delete(0, tk.END)
                self.macro_interval.insert(0, macro_cfg.get("interval", "100"))
                self.macro_repeat.set(macro_cfg.get("repeat", "1"))
            # 热键配置
            if "hotkeys" in config:
                self.hotkeys = config["hotkeys"]
                # 更新热键设置界面
                if hasattr(self, 'text_start_hotkey_var'):
                    self.text_start_hotkey_var.set(self.hotkeys.get("text_start", "Ctrl+Shift+1"))
                    self.text_stop_hotkey_var.set(self.hotkeys.get("text_stop", "Ctrl+Shift+Q"))
                    self.key_start_hotkey_var.set(self.hotkeys.get("key_start", "Ctrl+Shift+2"))
                    self.key_stop_hotkey_var.set(self.hotkeys.get("key_stop", "Ctrl+Shift+W"))
                    self.mouse_start_hotkey_var.set(self.hotkeys.get("mouse_start", "Ctrl+Shift+3"))
                    self.mouse_stop_hotkey_var.set(self.hotkeys.get("mouse_stop", "Ctrl+Shift+E"))
                    self.macro_record_hotkey_var.set(self.hotkeys.get("macro_record", "Ctrl+Shift+R"))
                    self.macro_play_hotkey_var.set(self.hotkeys.get("macro_play", "Ctrl+Shift+T"))
                    self.macro_stop_hotkey_var.set(self.hotkeys.get("macro_stop", "Ctrl+Shift+Y"))
               
                # 更新界面上的快捷键说明
                self.update_hotkey_labels()
        except Exception as e:
            messagebox.showerror("错误", f"加载配置时出错: {str(e)}")
if __name__ == "__main__":
    pyautogui.FAILSAFE = True
    pyautogui.PAUSE = 0.1
    root = tk.Tk()
    app = AutoInputTool(root)
    root.protocol("WM_DELETE_WINDOW", app.exit_app)
    root.mainloop()
由于源程序较大和源代码一并上传百度网盘
百度网盘链接:https://pan.baidu.com/s/1HzrQ6VkBz9mju39hNB7B3g?pwd=52pj 提取码: 52pj

热键, 鼠标

greatpeng   

发错版块了
忆惘惜
OP
  


greatpeng 发表于 2025-9-8 11:39
发错版块了

我看其他用户也是发的Ai生成软件到这个版,
请问我该发到什么版呢,还请告知,谢谢!
greatpeng   

『编程语言区』◇学习编程探讨编程技巧,共同分享程序源代码 ◇
忆惘惜
OP
  

好的, 谢谢
wwk2215   

貌似要发到原创版块?
PythonPan   


wwk2215 发表于 2025-9-8 11:43
貌似要发到原创版块?

AI生成不能发原创,除非有自己较多原创的部分
emhong   

感谢大佬分享
sunson1097   

应该发编程语言吧
ImpJ   

第一个原因应该是对应了ASCII码了
您需要登录后才可以回帖 登录 | 立即注册

返回顶部