Skip to main content
 首页 » 编程设计

python之在 python shell 中用点向前和向后打印文本 'Loading'

2025年02月15日9mate10pro

我想打印文本 '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) 

你怎么看?
如果你有那个点会前后移动然后请与我分享。
如果您需要更多信息,我随时可以提供给您。
谢谢

请您参考如下方法:

您可以在 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,它将继续以阻塞模式运行。