林新来的python,想知道如何做一个加载animation,而我的程序运行。 我需要这个,因为我不希望用户认为程序被陷入死循环。 我更喜欢像…
正在加载…(随着点的消失和逐一重现)
谢谢!
如果您的输出窗口支持回车符,您可以打印它以使光标返回到当前行的开头(只要您用逗号结束print
语句,不会自动打印换行符)。 接下来的打印将覆盖已经打印的内容。 你可以用这个来做很简单的一行动画。 例:
import time print "Starting program." print "Loading ", time.sleep(1) #do some work here... print "\rLoading. ", time.sleep(1) #do some more work here... print "\rLoading.. ", time.sleep(1) #do even more work... print "\rLoading...", time.sleep(1) #gratuitious amounts of work... print "\rLoading ",
… time.sleep(1)
是一个占位符,代表你想要做的实际工作。
结果:
Starting program. Loading
然后,一秒钟后:
Starting program. Loading.
然后,一秒钟后:
Starting program. Loading..
然后,一秒钟后:
Starting program. Loading...
然后,一秒钟后:
Starting program. Loading
等等
兼容性说明:在3.X中, print
不再是一个声明,“以逗号结束”技巧不再适用。 相反,请指定end
参数:
print("\rLoading...", end="")
我能想到的最正确的方法就是使用线程。
你会启动一个线程,开始显示一些程序正在做的事情,然后打开一个新的线程,实际上做的工作。
当完成工作的线程完成后,您可以继续执行其他任何程序。
在Windows命令提示符下运行时,这看起来不错,不知道Linux会如何喜欢它:
import threading import time import os import queue q = queue.Queue() q.put(False) class counter(object): def __init__(self): wait_label = "Loading" self.stop_flag = q.get() while not self.stop_flag: try: self.stop_flag = q.get_nowait() except: pass os.system('cls') # might need to change this command for linux wait_label += "." print(wait_label) time.sleep(1) class other(counter): def __init__(self): time.sleep(15) q.put(True) counter_thread = threading.Thread(None, counter) counter_thread.start() other_thread = threading.Thread(None, other) other_thread.start()