Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading animation in 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)

Thanks!

like image 444
Shengqi Wang Avatar asked Apr 16 '26 06:04

Shengqi Wang


1 Answers

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   ",

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

Result:

Starting program.
Loading

Then, one second later:

Starting program.
Loading.

Then, one second later:

Starting program.
Loading..

Then, one second later:

Starting program.
Loading...

Then, one second later:

Starting program.
Loading

etc.

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="")
like image 69
Kevin Avatar answered Apr 18 '26 20:04

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!