Python中的多条件if语句出现问题

2024-09-29 23:23:47 发布

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

我正在编写一个程序,如果鼠标在x秒内没有移动,它将移动鼠标(使用pyautogui库)。我在开始时取两次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语句保留得非常简单,因为我希望在继续程序之前它能正常工作。非常感谢您的帮助


Tags: import程序ifisposition语句鼠标print
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")

等等

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

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

话虽如此,看看你的代码,我想你的问题是你总是得到结果“!!!移动鼠标!!!”,即使你确实移动了鼠标

如果仔细查看代码,您会注意到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")

相关问题 更多 >

    热门问题