在python中加载动画 [英] Loading animation in python

查看:473
本文介绍了在python中加载动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,想知道如何在我的程序运行时制作加载动画.我需要这样做是因为我不希望用户认为该程序陷入了死循环.我喜欢类似...

Im new to python and was wondering how to make a loading animation while my program runs. I need this because I don't want users thinking that the program is caught in a dead loop. I prefer a something like...

正在加载...(点逐渐消失并重新出现)

Loading...(with the dots disappearing and reappearing one by one)

谢谢!

推荐答案

如果输出窗口支持回车符,则可以打印它以使光标返回到当前行的开头(前提是您结束带有逗号的语句,因此不会自动打印换行符).然后,后续打印将覆盖已打印的内容.您可以使用它来做非常简单的单行动画.示例:

If your output window supports the carriage return character, you can print it to make the cursor return to the beginning of the current line (provided you end your print statement with a comma, so a newline character isn't automatically printed). Then subsequent prints will overwrite what was already printed. You can use this to do very simple one line animation. Example:

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)是占位符,代表您要执行的实际工作.

... Where time.sleep(1) is a placeholder representing the actual work you want to do.

结果:

Starting program.
Loading

然后,一秒钟后:

Starting program.
Loading.

然后,一秒钟后:

Starting program.
Loading..

然后,一秒钟后:

Starting program.
Loading...

然后,一秒钟后:

Starting program.
Loading

兼容性说明:在3.X中,print不再是语句,并且以逗号结尾"的技巧也不再起作用.而是指定end参数:

Compatibility note: in 3.X, print is no longer a statement, and the "end with a comma" trick no longer works. Instead, specify the end parameter:

print("\rLoading...", end="")

这篇关于在python中加载动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆