如何让我的进度条在执行脚本时迭代?

问题描述 投票:0回答:2

我创建了一个 ui,它在单击按钮时运行 python 脚本。我包含了一个进度条来确认脚本何时完成。我不确定我的代码是否正确,因为当我单击按钮执行脚本时,进度条立即显示 100%。但是,执行代码的脚本仍在后台运行并在几秒钟后完成。

我使用 qt 设计器设置 ui。我正在运行 python 3.6 以下是进度条代码的片段:

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)

我试过将 time.sleep 设置从 1 更改为 0.1、0.00001。我尝试将进度条的代码更改为以下内容:

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())
python progress-bar python-3.6
2个回答
0
投票

为什么不尝试另一个模块,比如 tqdm:

pip install tqdm

这是非常直接的东西,比如:

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

0
投票

你可以使用线程。如果你没有线程模块使用

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

#...

© www.soinside.com 2019 - 2024. All rights reserved.