Search code examples
pythonpython-3.xloading

How To Code Loading Screen


How do programmers code proper loading screens? This is how I envision the code behind a loading screen, but I was wondering if there is a better way than just a bunch of conditional statements:

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);

Solution

  • I think you got it backward. I wouldn't code a loading screen based from a loading screen.

    Not sure about your language i hope you'll understand my c# prototype

    //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;
       }
    }
    

    what you see happening here is 2 threads. 1 thread (gui) that shows the loadingscreen for as long as the 2nd thread is doing work. This 2nd thread will send updates to the loading screen saying 'hey i did some more work, please update'

    Update Ah now i see you're using python. My idea should still stand though. You should loop over the work you need to be doing and then calculate the updates from there.