如何为加载屏幕生成滚动文本?

2024-10-02 00:34:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想制作一个加载屏幕来执行此操作,但会替换当前行:

LOADING
OADINGL
ADINGLO
DINGLOA
INGLOAD
...

我希望能够控制它一次打印的字母数。我尝试的是:

from itertools import cycle
from time import sleep

itr = cycle('LOADING')

for i in range(10):
    sleep(0.3)
    print('\r', ''.join(next(itr)))

但结果是:

 L
 O
 A
 D
 I
 N
 G
 L
 O
 A

Tags: fromimportfor屏幕time字母sleepitertools
2条回答

直接使用Python切片

from time import sleep
from sys import stdout

s = 'LOADING'
for i in range(10):
    sleep(0.3)
    if i > len(s): i = i - len(s)
    stdout.write('\r' + ''.join(s[i:] + s[:i]))

您需要在print中使用end关键字,以避免将每条消息打印到新行。我建议您构建要在每次迭代中显示的字符串,然后显示它。我不喜欢cycle方法,因为您无法很容易地索引到cycle对象。相反,我们可以使用常规的字符串索引和模运算符来确保我们不会越界,并且仍然可以一遍遍地“循环”字符串。你知道吗

import time

def scrolling_text(msg, n_chars):
    """
    Displays scrolling text of whatever 'msg' and ensures that only n_chars
    are shown at a time. If n_chars is greater than the length of msg, then
    the string displayed may "loop" around.

    Inputs:
        msg: str - The message to display
        n_chars: int - The number of characters to display at a time

    Outputs: Returns None, displays the scrolling text indefinitely.
    """
    len_msg = len(msg)
    counter = 0
    while True:
        displayed = ""
        for char in range(n_chars):
            displayed += msg[(counter+char)%len_msg]
        print(f"\r{displayed}", end="")
        time.sleep(0.05)
        counter = (counter + 1) % len_msg
    return

scrolling_text("LOADING", 25)

while True循环的每次迭代都将构建要显示的字符串(在嵌套的for loop中),然后显示它。在while循环结束时,拥有counter += 1就足够了,但是对于一个长时间运行的脚本,您可能会得到counter不必要的大。通过让counter = (counter + 1) % len_msg,我们可以确保counter永远不会超过消息的长度。你知道吗

相关问题 更多 >

    热门问题