如果您只使用一行代码,则很容易自行推出。 Chr(8)(退格)将光标向后移动一个空格。跟踪您在一行上打印了多少个字符,不要在末尾打印换行符,并打印足够的退格符以返回到您想要打印新文本的位置。如果新文本比已经存在的文本短,请打印足够的空格以擦除多余的内容。唯一真正的技巧是确保刷新输出,否则在打印换行符之前它不会显示。 (从 Python 3.3 开始,print() 函数上有一个 flush 参数,这很容易。)
这是一个小演示...我的目标是为Line 制作类似于 API 的东西,但实际上没有时间正确地完成它。不过,也许你可以从这里拿走它......
import time
from io import StringIO
class Line():
def __init__(self):
self.value = ""
def __call__(self, *args, start=0, sep=" "):
chars = 0
io = StringIO()
print(*args, file=io, end="", sep=sep)
text = io.getvalue()
self.value = (self.value[:start] + " " * (start - len(self.value))
+ text + self.value[start + len(text):])
print(self.value, chr(8) * len(self.value), sep="", end="", flush=True)
def __next__(self):
self.value = ""
print()
def greet():
line = Line()
line("hello", start=2)
time.sleep(1)
line("world", start=8)
time.sleep(1)
line("hi ", start=2)
time.sleep(1)
line("world ", start=7)
time.sleep(0.3)
line("world ", start=6)
time.sleep(0.3)
line("world ", start=5)
time.sleep(1)
line("globe", start=5)
time.sleep(1)
for _ in range(4):
for c in "! ":
line(c, start=10)
time.sleep(0.3)
line("!", start=10)
time.sleep(1)
next(line)
greet()