python中简单RGB动画的问题

问题描述

我正在尝试用 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?: 

我如何才能做到这一点?

解决方法

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

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,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()

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

帮助: Is it possible to print a string at a certain screen position inside IDLE?