在 python shell 中用点向前和向后打印文本“正在加载”

新手上路,请多包涵

我想打印 Text ‘Loading…’ 但它的点会前后移动(在 shell 中)。

我正在创建一个文字游戏,因此它看起来会更好。

我知道慢慢写一个字,但点也必须回去。

我在想我应该忘记点回来。为此:

 import sys
import time
shell = sys.stdout.shell
shell.write('Loading',"stdout")
str = '........'
for letter in str:
    sys.stdout.write(letter)
    time.sleep(0.1)

你怎么看?

如果你有那些点会前后移动然后请与我分享。

如果您需要更多信息,我准备提供给您。

谢谢

原文由 user8167727 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 423
2 个回答

检查具有许多功能的此模块 键盘。安装它,也许使用这个命令:

 pip3 install keyboard

然后在文件 textdot.py 中写入如下代码:

 def text(text_to_print,num_of_dots,num_of_loops):
    from time import sleep
    import keyboard
    import sys
    shell = sys.stdout.shell
    shell.write(text_to_print,'stdout')
    dotes = int(num_of_dots) * '.'
    for last in range(0,num_of_loops):
        for dot in dotes:
            keyboard.write('.')
            sleep(0.1)
        for dot in dotes:
            keyboard.write('\x08')
            sleep(0.1)

现在将文件从 python 文件夹粘贴到 Lib 中。

现在你可以像下面的例子一样使用它:

 import textdot
textdot.text('Loading',6,3)

谢谢

原文由 user8246379 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以在 STDOUT 中通过退格键( \b )使用回溯返回并“擦除”写入的字符,然后再次写入它们以模拟动画加载,例如:

 import sys
import time

loading = True  # a simple var to keep the loading status
loading_speed = 4  # number of characters to print out per second
loading_string = "." * 6  # characters to print out one by one (6 dots in this example)
while loading:
    #  track both the current character and its index for easier backtracking later
    for index, char in enumerate(loading_string):
        # you can check your loading status here
        # if the loading is done set `loading` to false and break
        sys.stdout.write(char)  # write the next char to STDOUT
        sys.stdout.flush()  # flush the output
        time.sleep(1.0 / loading_speed)  # wait to match our speed
    index += 1  # lists are zero indexed, we need to increase by one for the accurate count
    # backtrack the written characters, overwrite them with space, backtrack again:
    sys.stdout.write("\b" * index + " " * index + "\b" * index)
    sys.stdout.flush()  # flush the output

请记住,这是一个阻塞过程,因此您必须在 for 循环中进行加载检查,或者在单独的线程中运行加载,或者在单独的线程中运行它 - 它会继续运行在阻塞模式下,只要其本地 loading 变量设置为 True

原文由 zwer 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题