我正在尝试编写一个程序,当我移动鼠标光标时,它会不断显示鼠标光标的 x 和 y 坐标(自动化 python 第 417 页中的无聊内容)。
我尝试过调整 Try 语句的缩进,但我仍然 收到缩进错误消息。
import pyautogui
print('press Ctrl-C to quit.')
try:
while True:
except KeyboardInterrupt:
print('\nDone.')
x,y=pyautogui.position()
positionStr='X: ' + str(x).rjust(4) + 'Y: ' + str(y).rjust(4)
print(positionStr,end='')
print('\b'*len(positionStr),end='',flush=True)
我期望输出如下两行:
按 Ctrl-C 退出。 X:290 Y:424
但是我得到的输出是:
File "<ipython-input-2-b3f3ee266ed5>", line 6
except KeyboardInterrupt:
^
IndentationError: expected an indented block
最佳答案
代码应该是:
import pyautogui
print('press Ctrl-C to quit.')
try:
while True:
x,y=pyautogui.position()
positionStr='X: ' + str(x).rjust(4) + 'Y: ' + str(y).rjust(4)
print(positionStr,end='')
print('\b'*len(positionStr),end='',flush=True)
except KeyboardInterrupt:
pass
循环体位于异常处理 block 中。
好吧,至少现在它可以使输出更有用。需要的是仅打印位置自上次轮询以来发生变化的情况,并在循环中放入 time.sleep(0.1)
。
import pyautogui
import time
print('press Ctrl-C to quit.')
last_position = None
try:
while True:
x,y=position=pyautogui.position()
if position != last_position:
positionStr='X: ' + str(x).rjust(4) + 'Y: ' + str(y).rjust(4)
print(positionStr,end='')
print('\b'*len(positionStr),end='',flush=True)
last_position = position
time.sleep(0.1)
except KeyboardInterrupt:
pass
这会降低循环速度,并且仅在位置发生更改时才会打印。
关于python - "Where is the Mouse Right Now?",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56285477/