使用导入的modu中的变量向QProgressBar报告进度

2024-05-14 21:51:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个PyQT GUI应用程序progress_bar.py,有一个带有process_files()函数的外部模块worker.py,该模块使用文件列表执行一些例行程序,并使用percent变量报告当前进度。在

我要做的是使用QProgressBar.setValue()方法报告worker.process_files的当前进度,但我不知道如何实现它(回调函数或其他什么?)在

以下是我的模块:

进展_棒.py

import sys
from PyQt4 import QtGui
from worker import process_files


class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(100, 100, 300, 100)
        self.progress = QtGui.QProgressBar(self)
        self.progress.setGeometry(100, 50, 150, 20)
        self.progress.setValue(0)
        self.show()


app = QtGui.QApplication(sys.argv)
GUI = Window()
# process files and report progress using .setValue(percent)
process_files()
sys.exit(app.exec_())

工人.py

^{pr2}$

Tags: 模块函数pyimportselfsysguifiles
1条回答
网友
1楼 · 发布于 2024-05-14 21:51:10

使process_files函数成为一个生成器函数,该函数生成一个值(进度值),并将其作为回调传递到您的Window类中更新进度条值的方法。我在您的函数中添加了一个time.sleep调用,以便您可以观察进度:

import time
from worker import process_files

class Window(QtGui.QMainWindow):
    def __init__(self):
        ...

    def observe_process(self, func=None):
        try:
            for prog in func():
                self.progress.setValue(prog)
        except TypeError:
            print('callback function must be a generator function that yields integer values')
            raise


app = QtGui.QApplication(sys.argv)
GUI = Window()
# process files and report progress using .setValue(percent)
GUI.observe_process(process_files)
sys.exit(app.exec_())

工人.py

^{pr2}$

结果

处理后file2

enter image description here

相关问题 更多 >

    热门问题