python 中简单 RGB 动画的问题

Problem with simple RGB animation in python

我正在尝试用 python 制作一个简单的 RGB 动画,但我遇到了一些困难。

问题真的出在输出上,完全不符合我的要求。

代码:

def animation(message):
    def yuh():
        while True:
            colors = dict(Fore.__dict__.items())
            for color, i in zip(colors.keys(), range(20)):
                sys.stdout.write(colors[color] + message + "\r")
                sys.stdout.flush()
                sys.stdout.write('\b')
                time.sleep(0.5)
    threading.Thread(target=yuh).start()


def menu():
    animation("Hello Please select a option !")
    print("1 -- Test")
    qa = input("Answer?: ")

    if qa == 1:
        print("You did it !")
        sys.exit()

menu()

输出:

1 -- Test
Hello Please select a option !a option !

我最初的想法是输出看起来像这样:

Hello Please select a option !
1 -- Test
Answer?: 

我怎样才能做到这一点?

这是因为光标停留在最后一个 print/input 函数结束的位置。所以在 menu() 的第 3 行之后,光标位于“Answer?:”的末尾,这里首先打印消息,在“\r”回车 return 之后将光标拉到线。不过有一个解决方案:

def animation(message):
        def yuh():
                while True:
                        colors = dict(Fore.__dict__.items())
                        for color, i in zip(colors.keys(), range(20)):
                                sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (0, 0, colors[color] + message + "\r"))
                                sys.stdout.flush()
                                sys.stdout.write('\b')
                                time.sleep(0.5)
        threading.Thread(target=yuh).start()


def menu():
        animation("Hello Please select a option !")
        print("1 -- Test")
        qa = input("Answer?: ")

        if qa == 1:
                print("You did it !")
                sys.exit()

menu()

您可能需要编辑坐标,但除此之外它应该可以工作!

帮助来自: 是否可以在 IDLE 中的某个屏幕位置打印字符串?