Search code examples
pythontkinterpyautogui

Python tkinter with pyautogui


I want to create mouse mover, I write 2 separate codes. One for mouse moving and other for tkinter app, and now i don't know how to combine it. Can some help me? Thanks for your time!

Mouse Mover:

import pyautogui as pag
import random
import time

text = "AFK Bot is running. Each 5 seconds mouse will be moved."

print(text)

while True:
    x = random.randint(200,1000)
    y = random.randint(300,1200)
    pag.moveTo(x,y,0.5)
    time.sleep(5)

Tkinter app:

from tkinter import *

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

global is_on
is_on = True

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

def switch():
    global is_on
    if is_on:
        on_button.config(image=off)
        my_lable.config(text="The Switch is Off",
                        fg="grey")
        is_on = False
    else:
        on_button.config(image=on)
        my_lable.config(text="The Switch is On",
                        fg="green")
        is_on = True


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)


root.mainloop()

Solution

  • You can adapt your mouse move code to work with tkinter:

    import pyautogui as pag
    import random
    import time
    
    text = "AFK Bot is running. Each 5 seconds mouse will be moved."
    
    print(text)
    
    def mover(root):
        x = random.randint(200,1000)
        y = random.randint(300,1200)
        pag.moveTo(x,y,0.5)
        root.after(5000, lambda:mover(root))
    

    And call this once before mainloop:

    mover(root)
    root.mainloop()
    

    Update:

    To switch the mover() function on and off the same as the is_on variable, you could add a flag to the function:

    def mover(root):
        if mover.flag:
            x = random.randint(200,1000)
            y = random.randint(300,1200)
            pag.moveTo(x,y,0.5)
        root.after(5000, lambda:mover(root))
    

    and condition the flag:

    is_on = True
    mover.flag = is_on
    

    and update the flag:

    def switch():
        global is_on
        if is_on:
            on_button.config(image=off)
            my_lable.config(text="The Switch is Off",
                            fg="grey")
            is_on = False
        else:
            on_button.config(image=on)
            my_lable.config(text="The Switch is On",
                            fg="green")
            is_on = True
        mover.flag = is_on