Print Text 'Loading' with dots going forward and backward in python shell

后端 未结 4 1032
深忆病人
深忆病人 2021-01-13 07:01

I want to print Text \'Loading...\' But its dots would be moving back and forward (in shell).

I am creating a text game and for that it will look b

4条回答
  •  被撕碎了的回忆
    2021-01-13 07:27

    I believe the following code is what you are looking for. Simply thread this in your script, and it will flash dots while the user is waiting.

    ################################################################################
    """
    Use this to show progress in the terminal while other processes are runnning
                            - show_running.py -
    """
    ################################################################################
    #import _thread as thread
    import time, sys
    
    def waiting(lenstr=20, zzz=0.5, dispstr='PROCESSING'):
        dots   = '.' * lenstr
        spaces = ' ' * lenstr
        print(dispstr.center(lenstr, '*'))
        while True:
            for i in range(lenstr):
                time.sleep(zzz)
                outstr = dots[:i] + spaces[i:]
                sys.stdout.write('\b' * lenstr + outstr)
                sys.stdout.flush()
    
            for i in range(lenstr, 0, -1):
                time.sleep(zzz)
                outstr = dots[:i] + spaces[i:]
                sys.stdout.write('\b' * lenstr + outstr)   
                sys.stdout.flush()  
    #------------------------------------------------------------------------------#
    if __name__ == '__main__':
        import _thread as thread
        from tkinter import *
    
        root = Tk()
        Label(root, text="I'm Waiting").pack()
    
        start = time.perf_counter()
    
        thread.start_new_thread(waiting, (20, 0.5))
    
        root.mainloop()
    
        finish = time.perf_counter()
        print('\nYour process took %.2f seconds to complete.' % (finish - start))
    

提交回复
热议问题