我想创建一个执行此操作的加载屏幕,但替换当前行:
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
直接使用Python slicing:
s = 'LOADING'
for i in range(10):
sleep(0.3)
if i > len(s): i = i - len(s)
print(''.join(s[i:] + s[:i]))
输出:
LOADING
OADINGL
ADINGLO
DINGLOA
INGLOAD
NGLOADI
GLOADIN
LOADING
OADINGL
ADINGLO
您需要在end
中使用print
关键字,以避免将每条消息打印到新行。我建议您构建将在每次迭代中显示的字符串然后显示它的方法。我不喜欢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
永远不会超过消息的长度。