基于Python實現新年倒計時
更新時間:2023年01月09日 10:08:08 作者:Sir 老王
眼看馬上春節(jié)就要來臨了,所以滿懷期待的寫了一個Python新年倒計時的小工具!文中的示例代碼簡潔易懂,感興趣的小伙伴可以跟隨小編一起學習一下
不知不覺已經在家兩個月了,眼看馬上春節(jié)就要來臨了。滿懷期待的寫了一個新年倒計時的小工具!

設置新年時間后都能夠使用,打開軟件后可以自動計算到新年的倒計時情況。
UI界面及布局這塊一直使用的是PyQt5來實現的,若是沒有安裝使用pip的方式安裝一下即可。
pip?install?PyQt5
緊接著將PyQt5以及相關的模塊都導入到我們的代碼塊中準備開發(fā)。
#?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
業(yè)務邏輯不是很復雜,我們這次不通過子線程來實現業(yè)務邏輯,直接在主線程中開發(fā)界面布局和組件以及實現倒計時的過程。
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):
????????"""
????????業(yè)務初始化代碼塊
????????"""
????????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(
????????????"距離春節(jié):"?+?str(differ_day)?+?"天"?+?str(differ_hour)?+?"小時"?+?str(differ_minute)?+?"分鐘"?+?str(
????????????????differ_second)?+?"秒"?+?'\r')

使用python模塊主函數直接啟動春節(jié)倒計時桌面應用,就大功告成啦!
#?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新年倒計時內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

