不知不觉已经在家两个月了,眼看马上春节就要来临了。满怀期待的写了一个新年倒计时的小工具!
设置新年时间后都能够使用,打开软件后可以自动计算到新年的倒计时情况。
UI界面及布局这块一直使用的是PyQt5来实现的,若是没有安装使用pip的方式安装一下即可。
pip install PyQt5
紧接着将PyQt5以及相关的模块都导入到我们的代码块中准备开发。
# Importing all the classes from the QtWidgets module.
from PyQt5.QtWidgets import *
# Importing all the classes from the QtGui module.
from PyQt5.QtGui import *
# Importing the sys module.
import sys
# It imports all the classes from the QtCore module.
from PyQt5.QtCore import *
# Importing the datetime module.
import datetime
# Importing the math module.
import math
业务逻辑不是很复杂,我们这次不通过子线程来实现业务逻辑,直接在主线程中开发界面布局和组件以及实现倒计时的过程。
class CountDown(QWidget):
def __init__(self):
"""
A constructor. It is called when an object is created from a class and it allows the class to initialize the
attributes of a class.
"""
super(CountDown, self).__init__()
self.spring_date = datetime.datetime(2023, 1, 21, 0, 0, 0)
self.init_code()
def init_code(self):
"""
业务初始化代码块
"""
self.setWindowTitle('新年倒计时 公众号:Python 集中营')
self.setWindowIcon(QIcon('倒计时.png'))
self.resize(600, 400)
palette = QPalette()
palette.setBrush(QPalette.Background, QBrush(QPixmap("./背景.jpeg")))
self.setPalette(palette)
self.timer = QTimer()
self.timer.setInterval(1000)
self.timer.timeout.connect(self.refresh_count_down)
self.timer.start()
self.time_label = QLabel()
self.time_label.setAlignment(Qt.AlignCenter)
self.time_label.setStyleSheet('color:red;font:bold 28px;font-family:黑体')
vbox = QVBoxLayout()
vbox.addWidget(self.time_label)
self.setLayout(vbox)
def refresh_count_down(self):
"""
刷新页面倒计时时间
"""
current_date = datetime.datetime.now()
differ_day = (self.spring_date - current_date).days
seconds = (self.spring_date - current_date).seconds
differ_second = seconds % 60
differ_minute = seconds / 60 % 60
differ_hour = seconds / 60 / 60
if differ_hour > 24:
differ_hour = differ_hour - 24
differ_hour = math.floor(differ_hour)
differ_minute = math.floor(differ_minute)
self.time_label.setText(
"距离春节:" + str(differ_day) + "天" + str(differ_hour) + "小时" + str(differ_minute) + "分钟" + str(
differ_second) + "秒" + '\r')
使用python模块主函数直接启动春节倒计时桌面应用,就大功告成啦!
# A special variable in Python that evaluates to `True` if the module is being run as the main program.
if __name__ == '__main__':
app = QApplication(sys.argv)
main = CountDown()
main.show()
sys.exit(app.exec_())
到此这篇关于基于Python实现新年倒计时的文章就介绍到这了,更多相关Python新年倒计时内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!