PythonNoob
PythonNoob

Reputation: 235

How to get a working Progress Bar in python using multi-process or multi-threaded clients?

That's the basic idea.

I couldn't understand them while reading about all this in python's documentation. There's simply too much of it to understand it.

Could someone explain me how to get a working progress bar with a multi-threaded(or multi-process) client?

Or is there any other way to "update" progress bar without locking program's GUI?

Also I did read something about "I/O" errors when these types of clients try to access a file at the same time & X-server errors when an application doesn't call multi-thread libs correctly. How do I avoid 'em?

This time I didn't write code, I don't want to end with a zombie-process or something like that (And then force PC to shutdown, I would hate to corrupt precious data...). I need to understand what am I doing first!

Upvotes: 6

Views: 16662

Answers (1)

Luke.py
Luke.py

Reputation: 1005

Something like the below might get you started? - Ive tried to annotate as much as possible to explain the process.

from Tkinter import *
from Queue import Queue
import ttk, threading
import time

queue = Queue()
root = Tk()

# Function to do 'stuff' and place object in queue for later #
def foo():
    # sleep to demonstrate thread doing work #
    time.sleep(5)
    obj = [x for x in range(0,10)]
    queue.put(obj)

# Create thread object, targeting function to do 'stuff' #
thread1 = threading.Thread(target=foo, args=())

# Function to check state of thread1 and to update progressbar #
def progress(thread, queue):
    # starts thread #
    thread.start()

    # defines indeterminate progress bar (used while thread is alive) #
    pb1 = ttk.Progressbar(root, orient='horizontal', mode='indeterminate')

    # defines determinate progress bar (used when thread is dead) #
    pb2 = ttk.Progressbar(root, orient='horizontal', mode='determinate')
    pb2['value'] = 100

    # places and starts progress bar #
    pb1.pack()
    pb1.start()

    # checks whether thread is alive #
    while thread.is_alive():
        root.update()
        pass

    # once thread is no longer active, remove pb1 and place the '100%' progress bar #
    pb1.destroy()
    pb2.pack()

    # retrieves object from queue #
    work = queue.get()
    return work

work = progress(thread1, queue)
root.mainloop()

Hope this helps. Let me know what you think!

Upvotes: 10

Related Questions