【问题标题】:pyautogui don't recognize variablespyautogui 不识别变量
【发布时间】:2021-02-16 02:17:53
【问题描述】:

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

【问题讨论】:

  • 您希望从刚刚创建的条目中获得什么?你应该得到空字符串,int(...) 将引发异常。
  • 抱歉,刚刚创建的条目是什么?
  • coord1coord 是刚刚创建的两个条目。
  • 好的,那我该怎么办?
  • 这真的取决于你的程序设计。

标签: python tkinter pyautogui


【解决方案1】:

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

【讨论】:

  • 漂亮,谢谢,如果我有 15 分,我会投反对票
猜你喜欢
  • 2017-04-18
  • 2017-06-11
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-18
相关资源
最近更新 更多