2

我正在尝试制作一个不断打印鼠标位置直到停止的功能。导入pyautogui

import pyautogui

print('Press CTRL + "c" to stop')

while True:
    try:
        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:
        print('\nDone')
        break

预期的输出应如下所示:

X: 265 Y:634 只有一行不断刷新

但这是我得到的:

XXXXXXXXXXXXXXXXXXX:665 Y:587

XXXXXXXXXXXXXXXXXX:665 Y:587

XXXXXXXXXXXXXXXXXXXXX:665 Y:587

XXXXXXXXXX:718 Y:598

XXXXXXXXXXXX:1268 Y:766

删除 \b 字符 导入 pyautogui

print('Press CTRL + "c" to stop')

while True:
try:
    x, y = pyautogui.position()
    positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
    print(positionStr)
    print('\b' * len(positionStr), end = '', flush = True)
except KeyboardInterrupt:
    print('\nDone')
    break

X:830 Y:543

X:830 Y:543

X:830 Y:543

X:830 Y:543

完毕

4

2 回答 2

4

您可以使用回车打印该行,例如:

print(positionStr + '\r'),

像这样,下一行将替换现有行。而且您总是会看到一行更新为新的鼠标位置。

完整脚本:

#!/usr/bin/env python

import pyautogui

print('Press CTRL + "c" to stop')

while True:
    try:
        x, y = pyautogui.position()
        positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
        print(positionStr + '\r'),
    except KeyboardInterrupt:
        print('\nDone')
        break

编辑

正如下面评论中所说,这个解决方案可以在 Unix 平台上运行,但没有在其他平台上进行测试。由于不同的行尾约定,它应该会中断。感谢@Code-Apprentice 指出了这一点。

重新编辑

由于 OP 和 Code-Apprentice 的评论,我尝试像这样修复脚本,它按预期工作:

import pyautogui

print('Press CTRL + "c" to stop')

while True:
    try:
        x, y = pyautogui.position()
        positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
        print(positionStr, end=' ')
        print('\b' * (len(positionStr) + 1), end='')
    except KeyboardInterrupt:
        print('\nDone')
        break
于 2016-10-19T04:31:49.863 回答
1

您没有退格足够的字符。您忘记考虑额外的空格“结束”字符。当然,您应该能够end完全省略该参数。

于 2016-10-19T04:23:53.363 回答