python - "Where is the Mouse Right Now?"

标签 python user-interface jupyter-notebook

我正在尝试编写一个程序,当我移动鼠标光标时,它会不断显示鼠标光标的 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/

相关文章:

JavaFX setCellFactory 未设置我的项目

python - mongodb 连接字符串 uri 在 Kubernetes 中不起作用

python - 如何使用 Python 确定机器在给定所有位置数据的情况下移动的方向?

java - 按下Enter后如何防止StyledText中出现新行

python-3.x - 如何在Python中检查线程是否结束

r - 无法使用 install_github() : Git not installed? 安装 IRkernel

python - 如何在价格图表上自动调整 plotly Y 范围

python - 在 Jupyter 中支持 html 标签和从右到左的语言

python - pandas 中将字符串插入数据帧的 set_value 相当于什么

python - 在 matplotlib 极坐标图上旋转 theta=0