如何在打字机动画上添加某种突出显示,例如Python中的动画?

问题描述 投票:0回答:1

我为一个需要欢迎消息的项目编写了这个函数: 导入操作系统 导入系统

import time

message = "Helllo! \n\
We're glad to have your here! \n\
How may I assist you? \n\
"

def typewriter(message):
  for char in message:
    sys.stdout.write(char)
    sys.stdout.flush()
    
    if char != "\n" :
      time.sleep(0.1)
    else:
      time.sleep(1)

os.system("clear")

如果我想添加一个白色高亮覆盖每个字符 0.1 秒 3 次并跑一整圈,我该怎么做?

由于我是编码新手,所以现在我还没有想到解决这个问题的方法

python string animation
1个回答
0
投票

您可以使用 ANSI 代码来设置背景(看起来像高光)和文本颜色:

sys.stdout.write('\033[47m') # makes the background white (47)
sys.stdout.write('\033[30m') # makes the text white (30)
sys.stdout.write('\033[0m') # back to default style

将它们写在 sys.stdout.write(char) 之前,以便应用它们。

使用

'\b'
将光标向后移动一步,以默认样式的字符覆盖刚刚写入的高亮字符,然后再次以高亮样式覆盖(循环),以获得闪烁效果。您已经使用了睡眠功能,所以效果不会太快看到。

您可以将 和 样式代码组合在一行中,如下所示:

sys.stdout.write('\b\033[47m\033[30m')

你的问候语中有三个“L”; )

将它们放在一起可以得到:

import sys
import time

def typewriter(message):
    for char in message:
        
        sys.stdout.write('\033[0m')  # reset style to default
        sys.stdout.write(char) # print char with default style
        sys.stdout.flush()

        if char not in ['\n', ' ']:  
            for _ in range(3):
                sys.stdout.write('\b\033[47m\033[30m')  # move cursor back one space + highlight style
                sys.stdout.write(char)  # print char with highlight
                sys.stdout.flush()
                time.sleep(0.05)  # short pause to show the char with highlight

                sys.stdout.write('\b\033[0m')  # move cursor back + reset style to default
                sys.stdout.write(char)  # print char with default style
                sys.stdout.flush()
                time.sleep(0.1)  # pause before highlighting again

        else:
            if char == "\n":
                time.sleep(0.9)  # longer pause at new lines

os.system('cls' if os.name == 'nt' else 'clear') # clear terminal screen before starting 

message = "Hello! \n" \
"We're glad to have you here! \n" \
"How may I assist you? \n"

typewriter(message) # execute the function```
© www.soinside.com 2019 - 2024. All rights reserved.