从子例程更新进度条

时间:2014-09-22 08:47:51

标签: python progress-bar mainwindow

我想更新一个主窗口上的进度条,其中包含我在另一个子例程上执行的任务的进度,是否可能?

为了尽可能清楚,我会有两个文件:

在我的 Mainwindow.py 中,我会有类似的内容:

import Calculations

#some code
self.ui.progressBar
Calculations.longIteration("parameters")

然后我会有一个单独的文件进行计算: Calculations.py

def longIteration("parameters")

#some code for the loop

"here I would have a loop running"
"And I would like to update the progressBar in Mainwindow"

这可能吗?

或者它应该以不同的方式完成?

感谢。

1 个答案:

答案 0 :(得分:1)

最简单的方法是简单地传递GUI对象:

self.ui.progressBar
Calculations.longIteration("parameters", self.ui.progressBar)

并更新progressBar上的Calculations。但这有两个问题:

  • 您将GUI代码与Calculations混合,后者可能对此一无所知
  • 如果longIteration是一个长时间运行的函数,顾名思义,你将阻止你的GUI主线程,这将使许多GUI框架不满意(并且你的应用程序没有响应)。

另一个解决方案是在一个线程中运行longIteration,并传递一个用于更新进度条的回调函数:

import threading
def progress_callback():
    #update progress bar here
threading.Thread(target=Calculations.longIteration, args=["parameters", progress_callback]).run()

然后,在longIteration内,执行:

def longIteration( parameters, progress_callback ):
    #do your calculations
    progress_callback() #call the callback to notify of progress

如果需要,您可以修改progress_callback以获取参数,显然