Python pyQt:如何更新标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36606771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:05:33  来源:igfitidea点击:

pyQt: How do I update a label?

pythonpython-3.xpyqt5qt-designerqtwidgets

提问by T.T.

I created this simple UI with qtDesigner and I want to update my label every 10 seconds with the value of a function, but I have no idea how to do this.I've tried different things but nothing worked.

我用 qtDesigner 创建了这个简单的 UI,我想每 10 秒用一个函数的值更新我的标签,但我不知道如何做到这一点。我尝试了不同的东西,但没有任何效果。

def example():
    ...
    return text

UI:

用户界面:

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 300)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(165, 125, 61, 16))
        self.label.setObjectName("label")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", plsupdatethis)

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

回答by Brendan Abel

Ideally, you would create a subclass of QWidget(instead of simply instantiating it the way you are doing with Form). But here is a way you could do it with minimal changes.

理想情况下,您将创建一个子类QWidget(而不是像您那样简单地实例化它Form)。但是这里有一种方法可以让您以最少的更改来做到这一点。

You have a function that is capable of updating the label. Then use a QTimerto trigger it at regular intervals (in this case, every 10 seconds).

您有一个能够更新标签的函数。然后使用 aQTimer定期触发它(在这种情况下,每 10 秒)。

import datetime

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()

    def update_label():
        current_time = str(datetime.datetime.now().time())
        ui.label.setText(current_time)

    timer = QtCore.QTimer()
    timer.timeout.connect(update_label)
    timer.start(10000)  # every 10,000 milliseconds

    sys.exit(app.exec_())