终止线程

时间:2019-03-22 13:11:00

标签: python multithreading pyqt5

我在pyqt5上有一个应用程序。而且,如果我单击按钮时间,液晶显示屏将开始显示我创建的线程的倒计时。倒计时完成后,我不能使用相同的线程进行相同的操作。如何终止该线程,然后单击按钮重新启动

class window(QtWidgets.QMainWindow):   
   def __init__(self):      
     super(window,self).__init__()
     self.button1=QPushButton(self)
     self.lcd=QLCDNumber(self)
     self.tbutton1=threading.Thread(target=self.timing)
   def initUI(self):
       self.lcd.setVisible(False)
       self.button1.clicked.connect(self.timing)
   def timing(self):
      self.tbutton1.start()
      self.lcd.setVisible(True)
        timing=self.spin.value()
        for i in range(timing,-1,-1):
           time.sleep(1)
           if(i<10):
              self.lcd.display("00:0{}".format(i))
           else:
              self.lcd.display("00:{}".format(i))
        self.lcd.setVisible(False)
  if __name__=='__main__':       
     app=QApplication(sys.argv)
     win=window()
     sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:-1)

尝试一下:

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore    import *
from PyQt5.QtGui     import *
from PyQt5.QtWidgets import *
import threading


class window(QtWidgets.QMainWindow):   
    def __init__(self):      
        super(window,self).__init__()
        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)

        self.button1 = QPushButton("Start to countdown", self)
        self.lcd     = QLCDNumber(self)
        self.spin    = QSpinBox(self)

        grid  = QGridLayout(centralWidget)
        grid.addWidget(self.lcd)
        grid.addWidget(self.spin)
        grid.addWidget(self.button1)

        self.initUI()

    def initUI(self):
#        self.lcd.setVisible(False)
        self.button1.clicked.connect(self.timing)

    def timing(self):
        self.tbutton1 = threading.Thread(target=self.timingThread)
        self.tbutton1.start()
#        self.lcd.setVisible(True)

    def timingThread(self):        
        timing=self.spin.value()
        for i in range(timing, -1, -1):
#            time.sleep(1)
            QtCore.QThread.msleep(1000)
            if(i<10):
                self.lcd.display("00:0{}".format(i))
            else:
                self.lcd.display("00:{}".format(i))
#        self.lcd.setVisible(False)


if __name__=='__main__':       
    app = QApplication(sys.argv)
    win = window()
    win.show()
    sys.exit(app.exec_())

enter image description here