pyautogui不识别变量

2024-10-01 09:21:07 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个带有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)

Tags: 应用程序gettkinter错误place原因数字鼠标
1条回答
网友
1楼 · 发布于 2024-10-01 09:21:07

由于您在创建两个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()

相关问题 更多 >