我的线程正确吗?如果是,那么为什么代码不起作用?

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

我正在使用 PyQt4 在 python 中创建一个闹钟,并且我正在使用 LCD 显示小部件,它显示当前更新时间。为此,我正在使用线程。但我是新手所以问题是我不知道如何调试那个东西。

这是我的代码

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_())

我在 showTime() 函数中尝试 while 循环,然后它甚至没有在后台加载 GUI,只是 运行。 谢谢:)

Qt 不支持在主线程以外的线程中进行 GUI 操作。因此,当您从生成线程的上下文中调用 self.lcddisplay.display(showTime) 时,这是一个错误,Qt 将无法正常工作。

正如 tdelaney 在他的评论中建议的那样,处理此类事情的最佳方法是使用 QTimer 在适当的时间间隔发出信号,并在信号连接到的插槽中更新 lcddisplay。

(但是,如果您坚持使用线程,例如作为学习练习,那么您的派生线程将需要向主线程发送消息以告诉主线程进行显示更新,而不是尝试自己进行更新)

如其他地方所述,您不需要为此使用线程,一个简单的计时器即可。这是一个基本的演示脚本:

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_())