如何编码加载屏幕

How To Code Loading Screen

程序员如何编写正确的加载屏幕代码? 这就是我设想加载屏幕背后的代码的方式,但我想知道是否有比一堆条件语句更好的方法:

loading = 0
def load(percent):
    while percent <= 100:
        if percent == 0:
            foo.loadthing() # Just an example function
            percent += 10
        else if percent == 10:
            foo.loadthing()
            percent += 10

        ...

        else if percent == 100:
            foo.loadthing()
load(loading);

我想你搞反了。我不会根据加载屏幕编写加载屏幕代码。

不确定你的语言我希望你能理解我的 c# 原型

//Gui thread
var screen = LoadingScreen.Show();
await doWork(); //<- c# way to make doWork happen on 2nd thread and continue after the thread has been finished.
screen.Hide();

//somewhere else
async void doWork() {
   for(int i = 0; i < filesToLoad; ++i) {
      LoadFile(i);
      LoadingScreen.SetPercentage = 100.0 * i / filesToLoad;
   }
}

您在这里看到的是 2 个线程。只要第二个线程正在工作,第一个线程 (gui) 就会显示加载屏幕。第二个线程将更新发送到加载屏幕说 'hey i did some more work, please update'

更新 啊,现在我看到你正在使用 python。不过,我的想法应该仍然成立。你应该循环你需要做的工作,然后从那里计算更新。

如何使用 sys 模块创建加载屏幕: 它可能看起来不像,但这绝对有效..

import sys
import time
from time import sleep
for i in range(101):
    sys.stdout.write('\r')
    sys.stdout.write("[%-10s] %d%%" % ('='*i, 1*i))
    sys.stdout.flush()
    sleep(0.02)

这应该有效

import time
import replit
from random import randint
percent = 0
for i in range(100):
    replit.clear()
    percent +=1
    print("""
LOADING SCREEN
Status: loading

%"""+ str(percent)
         )
    time.sleep(randint(1,2))
    
print("Loading complete!\n")
print("Now...")
time.sleep(2)
print("What you have been waiting for...")
time.sleep(2)
print("Nothing")