pyautogui 不识别变量

pyautogui don't recognize variables

它是一个带有 tkinter 的应用程序,可以将鼠标移动到坐标指示的位置,所以我使用了普通变量,但由于某种原因它不起作用,鼠标只是不移动并且没有错误出现。我尝试取出变量并使用普通数字并且它工作正常,为什么它会出错的变量?错误是什么?

    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)

由于您在创建两个 Entry 小部件后立即获得它们的值,因此您应该得到空字符串,因为用户没有输入任何内容。所以 int(c, 0) 会异常失败。

您应该进行移动,例如,按钮的回调,以便用户可以在移动之前将值输入到两个 Entry 小部件中。

另外如果你想移动鼠标光标,你应该使用pyautogui.moveTo(...)而不是pyautogui.click(...)

下面是一个简单的例子:

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()