我创建了一个 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())
为什么不尝试另一个模块,比如 tqdm:
pip install tqdm
这是非常直接的东西,比如:
from time import sleep
from tqdm import tqdm
for i in tqdm(range(10)):
sleep(3)
你可以使用线程。如果你没有线程模块使用
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
#...