python中简单RGB动画的问题

2024-04-29 04:25:52 发布

您现在位置: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?: 

我怎样才能做到这一点


Tags: testmessagehellodefstdoutsysselectdict
1条回答
网友
1楼 · 发布于 2024-04-29 04:25:52

这是因为光标停留在上次打印/输入功能结束的位置。因此,在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, 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?

相关问题 更多 >