Search code examples
pythonmultithreadingpyqt4lcd

Is my threading proper ? if yes then why code is not working?


I am creating an alarm clock in python using PyQt4 and in that I am using LCD display widget, which display current updating time. For that I am using threading. But I am new to it so the problem is I have no clue how to debug that thing.

This is my code

import sys
from PyQt4 import QtGui, uic
import time
import os
from threading import Thread
class MyWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        uic.loadUi('AlarmClock_UI.ui', self)
        self.show()
        self.comboBox.setCurrentIndex(0)
        self.comboBox.currentIndexChanged.connect(self.getSelection)
        self.lineEdit.setText('Please select the reminder type')
        timeThread = Thread(target = self.showTime())
        timeThread.start()   


    def getSelection(self):
        if self.comboBox.currentIndex() == 1:
            self.lineEdit.setText('Select the alarm time of your choice')

        elif self.comboBox.currentIndex() == 2:
            self.lineEdit.setText('Use those dials to adjust hour and minutes')
        else:
            self.lineEdit.setText('Please select the reminder type')

    def showTime(self):        
           showTime = time.strftime('%H:%M:%S')
           self.lcdNumber.display(showTime)





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

I tried while loop in showTime() function then it was not even loading GUI just running in the background. Thanks :)


Solution

  • As has been said elsewhere, you do not need to use threading for this, as a simple timer will do. Here is a basic demo script:

    import sys
    from PyQt4 import QtCore, QtGui
    
    class Clock(QtGui.QLCDNumber):
        def __init__(self):
            super(Clock, self).__init__(8)
            self.timer = QtCore.QTimer(self)
            self.timer.timeout.connect(self.showTime)
            self.timer.start(1000)
            self.showTime()
    
        def showTime(self):
            time = QtCore.QTime.currentTime()
            self.display(time.toString('hh:mm:ss'))
    
    if __name__ == '__main__':
    
        app = QtGui.QApplication(sys.argv)
        window = Clock()
        window.setWindowTitle('Clock')
        window.setGeometry(500, 100, 400, 100)
        window.show()
        sys.exit(app.exec_())