每次按下按钮时都按一下按钮即可更改QLabel

时间:2019-04-25 02:02:53

标签: python pyqt pyqt4

我想打印出用户输入的一组3个数字的平均值。但是,每当我按下按钮时,文本就会彼此重叠

def Comp
    Average = QtGui.QLabel("The Students Average is " + str(self.average), self)
    Average.move(400,300)
    Average.setFont(QtGui.QFont('sanSerif',16))
    Average.resize(Average.sizeHint())
    Average.show()

btn = QtGui.QPushButton("Test",self)
btn.clicked.connect(self.comp)

我们将不胜感激任何帮助

1 个答案:

答案 0 :(得分:0)

每次按按钮都在创建一个新的QLabel,而必须重新使用QLabel。

from PyQt4 import QtCore, QtGui


class Widget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        self.average_label = QtGui.QLabel()
        self.average_label.setFont(QtGui.QFont("sanSerif", 16))
        self.button = QtGui.QPushButton("Test")
        self.button.clicked.connect(self.on_clicked)

        lay = QtGui.QVBoxLayout(self)
        lay.addWidget(self.average_label)
        lay.addWidget(self.button)

    @QtCore.pyqtSlot()
    def on_clicked(self):
        import random
        self.average = random.uniform(0, 100) # emulate average
        self.average_label.setText(
            "The Students Average is {}".format(self.average)
        )


if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())