You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何合并Python Tkinter界面与PyAutoGUI鼠标移动代码?

AFK Bot 整合方案:Tkinter开关控制鼠标自动移动

你需要解决的核心问题是避免while True阻塞Tkinter的主事件循环,同时用开关状态控制鼠标移动任务的启停。以下是整合后的完整代码:

import pyautogui as pag
import random
from tkinter import *

root = Tk()
root.title('AFK Bot!')
root.geometry("500x300")

# 全局变量控制开关状态
is_on = True

my_label = Label(root,
                 text="The Switch is On!",
                 fg="green",
                 font=("Helvetica", 32))
my_label.pack(pady=20)

def move_mouse():
    """执行一次鼠标移动,并根据开关状态决定是否继续调度"""
    if is_on:
        x = random.randint(200, 1000)
        y = random.randint(300, 1200)
        pag.moveTo(x, y, 0.5)
        # 5秒后再次调用自身,实现循环执行
        root.after(5000, move_mouse)

def switch():
    global is_on
    if is_on:
        on_button.config(image=off)
        my_label.config(text="The Switch is Off",
                        fg="grey")
        is_on = False
    else:
        on_button.config(image=on)
        my_label.config(text="The Switch is On",
                        fg="green")
        is_on = True
        # 开启开关后立即启动鼠标移动任务
        move_mouse()

# 加载开关状态图片
on = PhotoImage(file="images/on.png")
off = PhotoImage(file="images/off.png")

on_button = Button(root, image=on, bd=0, command=switch)
on_button.pack(pady=50)

# 程序启动时默认开启鼠标移动
move_mouse()

root.mainloop()

关键修改说明:

  • 替换阻塞循环:移除原代码中的while True,改用Tkinter的root.after(delay, func)方法实现定时任务,避免阻塞GUI的事件响应。
  • 封装鼠标移动逻辑:将鼠标移动代码封装为move_mouse()函数,每次执行后根据is_on状态,决定是否在5秒后再次调用自身。
  • 开关联动逻辑:开关从关闭切到开启时,主动触发move_mouse()启动任务;关闭开关时,is_on设为False,下一次调度的move_mouse()会直接退出,停止循环。
  • 初始状态处理:程序启动时默认开启状态,自动启动鼠标移动任务。

注意事项:

  • 确保images文件夹存在,且on.png、off.png图片路径正确,否则开关按钮会显示异常。
  • PyAutoGUI会直接操作系统光标,使用时注意不要干扰正常操作。

内容的提问来源于stack exchange,提问作者Arturs Golis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 05:15:33