Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a progress bar in a loop?

What is the easy method to update Tkinter progress bar in a loop?

I need a solution without much mess, so I can easily implement it in my script, since it's already pretty complicated for me.

Let's say the code is:

from Tkinter import *
import ttk


root = Tk()
root.geometry('{}x{}'.format(400, 100))
theLabel = Label(root, text="Sample text to show")
theLabel.pack()


status = Label(root, text="Status bar:", bd=1, relief=SUNKEN, anchor=W)
status.pack(side=BOTTOM, fill=X)

root.mainloop()

def loop_function():
    k = 1
    while k<30:
    ### some work to be done
    k = k + 1
    ### here should be progress bar update on the end of the loop
    ###   "Progress: current value of k =" + str(k)


# Begining of a program
loop_function()
like image 299
AltzeM Avatar asked Apr 09 '16 12:04

AltzeM


People also ask

How do I put progress bar in for loop?

Using Track Track is the quick way to add a progress bar to your code. You don't need to make major changes to the code, you can just insert the function where you declared the size of the for loop and you are good to go.

How do I update progress bar?

You can update the percentage of progress displayed by using the setProgress(int) method, or by calling incrementProgressBy(int) to increase the current progress completed by a specified amount. By default, the progress bar is full when the progress value reaches 100.

How do you code a progress bar in Python?

In order to create the progress bar in Python, simply add the highlighted syntax into the code: from tqdm import tqdm. tqdm(my_list)

How do you show the progress of a loop in Python?

Instead of printing out indices or other info at each iteration of your Python loops to see the progress, you can easily add a progress bar. wrap the object on which you iterate with pbar() . and it will display a progress that automatically updates itself after each iteration of the loop.


1 Answers

Here's a quick example of continuously updating a ttk progressbar. You probably don't want to put sleep in a GUI. This is just to slow the updating down so you can see it change.

from Tkinter import *
import ttk
import time

MAX = 30

root = Tk()
root.geometry('{}x{}'.format(400, 100))
progress_var = DoubleVar() #here you have ints but when calc. %'s usually floats
theLabel = Label(root, text="Sample text to show")
theLabel.pack()
progressbar = ttk.Progressbar(root, variable=progress_var, maximum=MAX)
progressbar.pack(fill=X, expand=1)


def loop_function():

    k = 0
    while k <= MAX:
    ### some work to be done
        progress_var.set(k)
        k += 1
        time.sleep(0.02)
        root.update_idletasks()
    root.after(100, loop_function)

loop_function()
root.mainloop()
like image 95
Pythonista Avatar answered Nov 13 '22 04:11

Pythonista