【问题标题】:"Where is the Mouse Right Now?"“老鼠现在在哪里?”
【发布时间】:2019-05-24 03:28:19
【问题描述】:

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

【问题讨论】:

标签: python user-interface jupyter-notebook


【解决方案1】:

代码应该是:

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

你在异常处理块中有循环体。

至少它现在可以使输出更有用。需要的是仅在位置从上次轮询时发生变化时才打印,并在循环中放入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

这会降低循环的速度,并且只有在位置发生变化时才会打印。

【讨论】:

  • 嗨 Dan D。我之前已经应用了你的策略,但是就像我说的,我希望程序只输出两行,所以当你在坐标周围移动光标时,坐标会发生变化。但是随着在程序末尾放置除键盘之外的技术,输出是无限的x和y坐标。
  • 您的意思是您还希望程序的新输出覆盖之前的输出吗?这可以做到,但也许我建议的添加会减少足够的输出。
  • D,哇,这样更好。谢谢
  • @Dan D,哇,这样更好。
猜你喜欢
  • 1970-01-01
  • 2022-06-16
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
  • 1970-01-01
  • 1970-01-01
  • 2019-10-14
  • 2018-08-04
相关资源
最近更新 更多