【问题标题】:Issue with Multiple condition if statement Python多个条件if语句Python的问题
【发布时间】:2021-05-11 01:08:19
【问题描述】:

如果鼠标在 x 秒内没有移动,我正在编写一个程序来移动鼠标(使用 pyautogui lib)。我在开始时两次获取 X,Y 坐标,然后在延时后再次获取,然后将 X 和 Y 值与前一个值进行比较。我的 if 语句存在问题,理论上应该执行上述操作,但经过测试后,它无法按预期工作。任何人都可以建议我可以进行的任何编辑来解决这个简单的问题。

这是我的代码:

#!/usr/bin/env python3
import pyautogui
import time


currentMouseX, currentMouseY = pyautogui.position() #Grabs X,Y mouse position
print("position X1 is", currentMouseX)
print("position Y1 is", currentMouseY)

X1 = currentMouseX
Y1 = currentMouseY

time.sleep(3)

currentMouseX2, currentMouseY2 = pyautogui.position() #Grabs second X,Y position after 3 seconds 
X2 = currentMouseX
Y2 = currentMouseY

print("position X2 is", currentMouseX2)
print("position Y2 is", currentMouseY2)

**if ((X1 == X2) and (Y1 == Y2)):
    print ("!!! MOVE MOUSE !!!")
else:
    print("Mouse does not need to be moved")**

仅供参考:我让 if 语句非常简单,因为我希望它在继续程序之前工作。非常感谢任何帮助。

【问题讨论】:

  • 程序输出的值是什么? X1、Y1、X2 和 Y2(因为我认为这可能是一些浮点比较错误)
  • 您遇到的实际问题是什么?说它没有按预期工作是没有意义的,而不说它做了什么或你期望什么。
  • X2 = currentMouseX 应该是 X2 = currentMouseX2 (与 y 值相同),否则您总是将初始坐标与其自身进行比较。投票结束为错字。

标签: python python-3.x if-statement pyautogui


【解决方案1】:

注意:说你的代码没有按预期工作是没有意义的,除非你解释它应该做什么以及它实际上在做什么。

话虽如此,查看您的代码,我假设您的问题是您总是得到结果“!!! MOVE MOUSE !!!”,即使您确实移动了鼠标。

如果您仔细查看您的代码,您会注意到 X1 和 X2 将始终相同,Y1 和 Y2 也将始终相同,因为您使用以下方式分配它们:

X1 = currentMouseX
Y1 = currentMouseY

X2 = currentMouseX
Y2 = currentMouseY

不覆盖currentMouseY。相反,您将第二个坐标加载到currentMouseX2currentMouseY2

简而言之,您的代码使用了许多不必要的分配方式。相反,请执行以下操作:

#!/usr/bin/env python3
import pyautogui
import time


prev = pyautogui.position() #Grabs X,Y mouse position
print("position X1 is", prev[0])
print("position Y1 is", prev[1])

time.sleep(3)

after = pyautogui.position() #Grabs second X,Y position after 3 seconds

print("position X2 is", after[0])
print("position Y2 is", after[1])

if (prev == after):
    print ("!!! MOVE MOUSE !!!")
else:
    print("Mouse does not need to be moved")

【讨论】:

    【解决方案2】:

    与其测试是否相等,不如测试差异是否低于某个阈值:

    moveThresh = 4 # (or suitable small number)
    XMove = X2 - X1
    YMove = Y2 - Y1
    if abs(XMove) < moveThresh and abs(YMove) < moveThresh:
        # treat tiny moves as no move
        print("The mouse is effectively stationary & the cat is bored")
    else:
        print("The mouse is moving & the cat is interested")
    

    等等

    除非你要连接一些有趣的硬件,否则我怀疑你会移动鼠标——只移动鼠标指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      • 2013-12-17
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      • 2015-01-20
      相关资源
      最近更新 更多