Home > Back-end >  ttk Progressbar display only in the end of the process
ttk Progressbar display only in the end of the process

Time:05-21

As per object, the progress bar is displayed only at the end of the completion of the for loop. Instead I would like it to show the progress of the cycle step by step.

from tkinter import ttk
from tkinter import *
import time

def inner_loop_func():
    k = 0
    for i in range(10**5):
        k=k 1
    print("k: ",k)

def loop_fun():

    p = ttk.Progressbar(root, orient="horizontal", length=300, mode="determinate", takefocus=True, maximum=100)
    p['value'] = 0
    p.pack()

    end = 100
    for i in range(end):
        start(end,p)
        inner_loop_func()
        print(i," of ", end)

def start(end,p):

    if p['value'] < 300:
        p['value']  = (300/end)
    else:
        print("finish")

if __name__ == "__main__":

    root = Tk()
    loop_fun()
    root.mainloop()

CodePudding user response:

I think you would need to place your progress bar on a thread. I have done something similar in the past on a daemon thread. However I changed the mode to indeterminate so that the progress stops when the function is complete. Then I just called the thread in place of your function I hope this helps.

from tkinter import ttk
from tkinter import *
import time
import threading


def loop_fun_thread():
    run_thread = threading.Thread(target=loop_fun)
    run_thread.daemon = True
    run_thread.start()

    
def inner_loop_func():
    k = 0
    for i in range(10**5):
        k=k 1
    print("k: ",k)

def loop_fun():

    p = ttk.Progressbar(root, orient="horizontal", length=300, mode="indeterminate", takefocus=True, maximum=100)
    p['value'] = 0
    p.pack()

    end = 100
    for i in range(end):
        start(end,p)
        inner_loop_func()
        print(i," of ", end)

def start(end,p):

    if p['value'] < 300:
        p['value']  = (300/end)
    else:
        print("finish")

if __name__ == "__main__":

    root = Tk()
    loop_fun_thread()
    root.mainloop()

CodePudding user response:

Use p.update() inside the loop_fun function for loop:

for i in range(end):
    start(end, p)
    inner_loop_func()
    print(i, " of ", end)
    p.update()
  • Related