用python做一个10分钟倒计时QT界面,倒计时开始要显示2秒钟‘答辩开始’,剩余俩分钟的时候屏幕变成黄色,最后十秒钟变成红色,计时结束后要显示‘答辩结束’,QT窗口要能自适应屏幕大小。
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QDesktopWidget
from PyQt5.QtGui import QFont
from PyQt5.QtCore import QTimer, Qt
class Countdown(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('倒计时')
self.setWindowIcon(self.style().standardIcon(1))
self.resize(self.width(), self.height()) # 默认大小
# 窗口居中显示
screen = QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)
# 垂直布局
layout = QVBoxLayout()
# 显示文字标签
self.label = QLabel('答辩开始', self)
font_size = screen.width() // 20 # 字体大小设置为相对于屏幕宽度的比例
font = QFont('Microsoft YaHei', font_size, QFont.Bold)
self.label.setFont(font)
self.label.setAlignment(Qt.AlignCenter) # 居中对齐
layout.addWidget(self.label)
# 水平布局
h_layout = QHBoxLayout()
# 开始按钮
self.start_button = QPushButton('开始', self)
self.start_button.clicked.connect(self.start_timer)
h_layout.addWidget(self.start_button)
# 重置按钮
self.reset_button = QPushButton('重置', self)
self.reset_button.clicked.connect(self.reset_timer)
h_layout.addWidget(self.reset_button)
layout.addLayout(h_layout)
self.setLayout(layout)
# 倒计时时间(秒)
self.time_total = 10 * 60
self.time_left = self.time_total
# 倒计时器
self.timer = QTimer()
self.timer.setInterval(1000)
self.timer.timeout.connect(self.update_timer)
def start_timer(self):
self.start_button.setEnabled(False)
self.label.setText('答辩开始')
self.time_left = self.time_total + 5 # 显示5秒钟“答辩开始”
self.timer.start()
def reset_timer(self):
self.start_button.setEnabled(True)
self.label.setText('答辩开始')
self.time_left = self.time_total
self.timer.stop()
def update_timer(self):
self.time_left -= 1
if self.time_left == 2 * 60 : # 剩余2分钟时,标签背景变为黄色
self.label.setStyleSheet('background-color: yellow')
if self.time_left == 10: # 剩余10秒钟时,标签背景变为红色
self.label.setStyleSheet('background-color: red')
if self.time_left <= 0: # 倒计时结束,显示“答辩结束”
self.label.setStyleSheet('')
self.label.setText('答辩结束')
self.timer.stop()
self.start_button.setEnabled(True)
# 获取屏幕的宽度
screen_width = QDesktopWidget().screenGeometry().width()
# 动态调整字体大小
font_size = screen_width // 10
font = QFont('Microsoft YaHei', font_size, QFont.Bold)
self.label.setFont(font)
# 更新时间标签
minutes = self.time_left // 60
seconds = self.time_left % 60
self.label.setText(f'{minutes:02d}:{seconds:02d}')
if __name__ == '__main__':
app = QApplication(sys.argv)
countdown = Countdown()
countdown.showMaximized() # 全屏显示
sys.exit(app.exec_())