<p>我看到这是一个线程问题,而不仅仅是一个动画加载问题。这个QA线程中提供的大多数答案都只提供了一个伪代码,让读者自己处理。</p>
<p>下面是我试图用<strong>线程和动画加载的工作示例给出的答案。</p>
<p><em>读取器可以根据其需要进行修改。</p>
<h2>#导入python包</h2>
<pre><code>import sys, time, threading
</code></pre>
<h2>#定义流程</h2>
<pre><code> # Here is an example of the process function:
def the_process_function():
n = 20
for i in range(n):
time.sleep(1)
sys.stdout.write('\r'+'loading... process '+str(i)+'/'+str(n)+' '+ '{:.2f}'.format(i/n*100)+'%')
sys.stdout.flush()
sys.stdout.write('\r'+'loading... finished \n')
</code></pre>
<h2>#定义动画角色功能:</h2>
<pre><code>def animated_loading():
chars = "/—\|"
for char in chars:
sys.stdout.write('\r'+'loading...'+char)
time.sleep(.1)
sys.stdout.flush()
</code></pre>
<h2>#定义线程的名称和目标</h2>
<pre><code>the_process = threading.Thread(name='process', target=the_process_function)
</code></pre>
<h2>#启动线程</h2>
<pre><code>the_process.start()
</code></pre>
<h2>#当进程处于活动状态时,调用<code>animated_loading()</code>函数</h2>
<pre><code>while the_process.isAlive():
animated_loading()
</code></pre>
<p>注释行中概述了主要步骤。</p>