Search code examples
pythontkinterpyautogui

pyautogui don't recognize variables


Its a app with tkinter to move the mouse where the coordinates indicate, so I used normal variables, but for some reason it does't work, the mouse just don't move and non error apear. I tried take out the variables and use normal numbers and it worked fine, why with the variables it bugs? And what is the error?

    coord1= Entry(win, width=10)
    coord1.place(x=300, y=125)
    coord2= Entry(win, width=10)
    coord2.place(x=400, y=125)

    b = coord2.get()
    c = coord1.get()
    d = int(c,0)
    e = int(b,0)
    pyautogui.click(d, e)

Solution

  • Since you get the values of the two Entry widgets right after they are created, you should get empty strings as the user has not input anything. So int(c, 0) will fail with exception.

    You should do the move in, for example, the callback of a button so that user can input values into the two Entry widgets before doing the move.

    Also if you want to move the mouse cursor, you should use pyautogui.moveTo(...) instead of pyautogui.click(...).

    Below is an simple example:

    import tkinter as tk
    import pyautogui
    
    win = tk.Tk()
    win.geometry('500x200')
    
    tk.Label(win, text='X:').place(x=295, y=125, anchor='ne')
    coord1 = tk.Entry(win, width=10)
    coord1.place(x=300, y=125)
    
    tk.Label(win, text='Y:').place(x=395, y=125, anchor='ne')
    coord2 = tk.Entry(win, width=10)
    coord2.place(x=400, y=125)
    
    # label for showing error when user input invalid values
    label = tk.Label(win, fg='red')
    label.place(x=280, y=80, anchor='nw')
    
    def move_mouse():
        label.config(text='')
        try:
            x = int(coord1.get().strip(), 0)
            y = int(coord2.get().strip(), 0)
            pyautogui.moveTo(x, y) # move the mouse cursor
        except ValueError as e:
            label.config(text=e) # show the error
    
    tk.Button(win, text='Move Mouse', command=move_mouse).place(relx=0.5, rely=1.0, y=-10, anchor='s')
    
    win.mainloop()