Search code examples
pythontkinterprogress-barttk

How to add tkinter progress bar indeterminate with function


from tkinter import *
from tkinter import ttk

def DOTEST_GUI():
    GUI = Tk()
    w = 1920
    h = 1080
    ws = GUI.winfo_screenwidth()
    hs = GUI.winfo_screenheight()
    x = (ws/2) - (w/2)
    y = (hs/2) - (h/2)
    GUI.geometry(f'{w}x{h}+{x:.0f}+{y:.0f}')

    def start_p():
        progress.start(5)

    def stop_P():
        progress.stop()

    def print_cf(event = None):
        import time
        print('s')
        start_p()
        time.sleep(5)
        stop_P()

    B_TEST = ttk.Button(GUI, text = "test", width = 15, command = print_cf)
    B_TEST.pack()

    progress = ttk.Progressbar(GUI, orient = HORIZONTAL, length = 100, mode = 'indeterminate')
    progress.pack(pady = 10)

    GUI.bind("<Return>", print_cf)

    GUI.focus()
    GUI.mainloop()

DOTEST_GUI()

follow this code progress bar is not running properly.

I tried to remove stop_P(), it's work after 5 second of time.sleep(5).

I would like it to start running progress 5 second until the stop_P() code.


Solution

  • If you want to run a Progressbar for a set amount of time and then stop it, you could do something like this. Consolidate the print_cf function to start and stop the progress and set a range of 5, sleep for 1 second in between and then stop the Progressbar. Placing it on a thread would allow you to do something more time consuming than sleeping one second and printing something.

    from tkinter import *
    from tkinter import ttk
    import time
    import threading
    
    
    
                        
    def DOTEST_GUI():
        GUI = Tk()
        w = 1920
        h = 1080
        ws = GUI.winfo_screenwidth()
        hs = GUI.winfo_screenheight()
        x = (ws/2) - (w/2)
        y = (hs/2) - (h/2)
        GUI.geometry(f'{w}x{h}+{x:.0f}+{y:.0f}')
    
    
        def run_thread():
            execute_thread = threading.Thread(target=print_cf)
            execute_thread.start()
    
            
        def print_cf(event = None):
            progress.start()
            print('s')
            for i in range(5):
                print(i)
                time.sleep(1)
                if i ==4:
                    progress.stop()
    
    
        B_TEST = ttk.Button(GUI, text = "test", width = 15, command = run_thread)
        B_TEST.pack()
    
        progress = ttk.Progressbar(GUI, orient = HORIZONTAL, length = 100, mode = 'indeterminate')
        progress.pack(pady = 10)
    
        GUI.bind("<Return>", print_cf)
    
        GUI.focus()
        GUI.mainloop()
            
    
    DOTEST_GUI()