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

5 python shell python-3.x

我想打印 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)
Run Code Online (Sandbox Code Playgroud)

你怎么认为?
如果你有那个点会来回移动那么请与我分享。
如果您想了解更多信息,我已准备好提供给您。
谢谢

zwe*_*wer 7

您可以通过 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
Run Code Online (Sandbox Code Playgroud)

请记住,这是一个阻塞过程,因此您必须在循环内进行加载检查for,或者在单独的线程中运行加载,或者在单独的线程中运行它 - 只要它的局部loading变量设置为True


小智 5

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

pip3 install keyboard
Run Code Online (Sandbox Code Playgroud)

然后在文件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)
Run Code Online (Sandbox Code Playgroud)

现在将文件从 python 文件夹粘贴到Lib 中
现在你可以像下面的例子一样使用它:

import textdot
textdot.text('Loading',6,3)
Run Code Online (Sandbox Code Playgroud)

谢谢