import sys
from PyQt5.Qt import *
class Window(QWidget):
def __init__(self):
super().__init__()
self.label = None
self.button = None
self.setWindowTitle("计时器")
self.resize(300, 300)
self.timer_id = None
self.second_number = 10
self.timer_interval = 1000
self.setup_ui()
self.custom_action()
def setup_ui(self):
self.label = QLabel(self)
self.label.setText(str(self.second_number))
self.label.move(100, 100)
self.button = QPushButton(self)
self.button.setText("开始计时")
self.button.move(100, 200)
def custom_action(self):
self.button.clicked.connect(self.timer_start)
def timerEvent(self, a0) -> None:
self.second_number -= 1
self.label.setText(str(self.second_number))
self.resize(self.width()+10,self.height()+10)
if self.second_number == 0:
self.killTimer(self.timer_id)
def timer_start(self):
if self.second_number != 0:
self.timer_id = self.startTimer(self.timer_interval)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())