在QWidget上同时显示日期和时间

date.py

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

class Date(QWidget):
    def __init__(self, parent = None):
        super().__init__(parent)
        self.setWindowTitle(self.tr('显示日期'))
        self.resize(500,400)
        #self.setFixedSize(500,400)
        self.layout = QHBoxLayout()
        self.label = QLabel(self)
        self.date = QDate.currentDate()
        dateStr = self.date.toString('yyyy/MM/dd/dddd')
        #print(self.date.dayOfWeek())
        #print(self.date.dayOfYear())
        formatedStr = dateStr[:10] + '  '+ dateStr[11:]
        self.label.setText(formatedStr)

        font = QFont()
        font.setFamily(self.tr('微软雅黑'))
        font.setPointSize(15)
        self.label.setFont(font)
        self.label.setAlignment(Qt.AlignCenter)
        #self.label.setFrameShape(QFrame.Box)

        self.layout.addWidget(self.label)
        self.setLayout(self.layout)

time_1.py (文件的命名不能和python已有的库或函数同名)

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

class Time(QWidget):
    def __init__(self, parent = None):
        super().__init__(parent)

        self.layout = QHBoxLayout()
        self.lcd = QLCDNumber(self)
        font = QFont()
        font.setFamily(self.tr('微软雅黑'))
        font.setPointSize(12)
        font.setBold(True)
        self.lcd.setFont(font)


        self.timer = QTimer(self)   #使用QTimer时,一定要为其指定父部件
        self.timer.timeout.connect(self.updateTime)
        self.timer.start(1000)

        '''
        #不把timer指定为类的属性也可以,但是一定要为QTimer指定父部件
        timer = QTimer(self)
        timer.timeout.connect(self.updateTime)
        timer.start(1000)
       '''

        self.layout.addWidget(self.lcd)
        self.setLayout(self.layout)

    def updateTime(self):
        time = QTime.currentTime()
        if time.second()%2 == 0:
            timeStr = time.toString('hh:mm')
        else:
            timeStr = time.toString('hh mm')
        self.lcd.display(timeStr)
showdateandtime.py
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys
import time_1 #文件名不要与已有的库或函数重名,命名为time就不行,所以就改为了time_1
import date


class DateAndTime(QWidget):
    def __init__(self, parent = None):
        super().__init__(parent)
        self.setWindowTitle(self.tr('日期和时间'))
        self.setGeometry(600,350,250,150)
        self.setFixedSize(250,150)
        self.setStyleSheet('background-color:green')
        self.layout = QVBoxLayout()
        self.date = date.Date(self)
        self.time = time_1.Time(self)
        self.layout.addWidget(self.date)
        self.layout.addWidget(self.time)
        self.setLayout(self.layout)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    dt = DateAndTime()
    dt.show()
    sys.exit(app.exec_())
原文地址:https://www.cnblogs.com/ACPIE-liusiqi/p/10613547.html