How do I get my progress bar to iterate while a script is being executed?

Question:

I created a ui that runs a python script on a button click. I included a progress bar to confirm when the script has completed. I’m not sure I have the code correct because when I click the button to execute the script, the progress bar instantly shows 100%. However, the script that’s executing the code is still running in the background and completes a few seconds later.

I setup the ui using qt designer. I’m running python 3.6 Below is a snippet of the progress bar code:

def progress(self):
        loop_count = 100
        self.progressBar.setValue(loop_count)
        
        while True:
            #the script that's executing based o the button click
            with open("Python-Test1.py") as f:
                 exec(f.read())
                 loop_count += 1
                 if loop_count >= 100:
                     break
                 time.sleep(1)

I’ve tried changing the time.sleep setting from 1 to 0.1, 0.00001. I’ve tried changing the code for the progress bar to the following:

def progress(self):
     count = 100
       for i in range(100):
             count += 1
             self.progressBar.setValue(count)
             #the script that's executing based o the button click
             subprocess.run(['python', 'Python-Test1.py'])
             time.sleep(0.1) 
             with open("Python-Test1.py") as f:
                 exec(f.read())
Asked By: Clickit74

||

Answers:

Why not try another module, like tqdm:

pip install tqdm

It is something really direct, like:

from time import sleep
from tqdm import tqdm
for i in tqdm(range(10)):
    sleep(3)
Answered By: Magaren

You could use threading. If you don’t have the threading module use

pip install threading


import threading
def progress(self):
loop_count = 100
self.progressBar.setValue(loop_count)

while loop_count # Start whatever where the progress bar is needed
t = threading.Thread(target=progress)
t.start()
# Run whatever you need, the progress bar should be running

#...

Answered By: STU NATHANIEL COLE
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.