如何停止在pyqt4中的按钮上打印数字

时间:2019-03-11 18:04:39

标签: python-3.x user-interface pyqt4

我想在pyqt4的GUI中开始打印数字,但是当我按下开始按钮时,它冻结了,我必须关闭窗口,我想单击一个按钮来启动psocess,然后用另一个按钮停止,在这里我让我的代码

这是我尝试启动和停止该过程的部分

class LecturaFrecuencia(QMainWindow):
    """docstring for LecturaFrecuencia"""
    def __init__(self, parent):
        super(LecturaFrecuencia, self).__init__(parent)
        uic.loadUi('frecuencia.ui', self)
        global START
        self.button_volver.clicked.connect(self.regresar)
        self.button_terminar.clicked.connect(self.terminar_monitoreo)
        self.button_guardar.clicked.connect(self.guardar)
        self.button_iniciar.clicked.connect(self.iniciarLectura)

    def iniciarLectura(self):
        START = 1
        while START :
            pqrst= random.randint(55,101)
            time.sleep(1.0)
            print(str(pqrst))
            self.pqrst.setText(str(pqrst))
            if self.button_terminar.isChecked():
                START = 0
            else:
                pass

1 个答案:

答案 0 :(得分:0)

切勿在GUI线程中使用time.sleep(),因为它将冻结它。如果要执行定期任务,请使用QTimer:

import random
from PyQt4 import QtCore, QtGui, uic

class LecturaFrecuencia(QtGui.QMainWindow):
    """docstring for LecturaFrecuencia"""
    def __init__(self, parent=None):
        super(LecturaFrecuencia, self).__init__(parent)
        uic.loadUi('frecuencia.ui', self)

        timer = QtCore.QTimer(
            self,
            interval=1000,
            timeout=self.processing
        )

        self.button_iniciar.clicked.connect(timer.start)
        self.button_terminar.clicked.connect(timer.stop)

    @QtCore.pyqtSlot()
    def processing(self):
        pqrst = random.randint(55,101)
        self.pqrst.setText("{}".format(pqrst))

if __name__ == '__main__':
    import sys 
    app = QtGui.QApplication(sys.argv)
    w = LecturaFrecuencia()
    w.show()
    sys.exit(app.exec_())