import datetime
import sys
import traceback
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class Main(QDialog):
    """定时器Demo"""
    def __init__(self, parent=None):
        try:
            super(Main, self).__init__(parent)
            self.init_ui()
            self.init_slot()
            # 定时器
            self.timer = QTimer(self)
            self.timer.timeout.connect(self.reload_time_string)
        except:
            traceback.print_exc()

    def init_ui(self):
        try:
            self.resize(240, 120)
            self.setWindowTitle("定时器demo")
            # label控件： 显示时间
            self.label = QLabel(self)
            time_string = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            self.label.setText(time_string)
            # 定时器开始按钮
            self.pushButton_start = QPushButton(self)
            self.pushButton_start.setText("开始")
            # 定时器结束按钮
            self.pushButton_stop = QPushButton(self)
            self.pushButton_stop.setText("结束")
            # 定时器刷新时间
            self.spinBox = QSpinBox(self)
            self.spinBox.setMinimum(1)
            self.spinBox.setMaximum(100)
            # 布局
            layout = QHBoxLayout()
            layout.addWidget(self.label)
            layout.addWidget(self.pushButton_start)
            layout.addWidget(self.pushButton_stop)
            layout.addWidget(self.spinBox)

            self.setLayout(layout)
        except:
            traceback.print_exc()

    def init_slot(self):
        try:
            self.pushButton_start.clicked.connect(self.start_timer)  # 开始刷新
            self.pushButton_stop.clicked.connect(self.stop_timer)  # 停止刷新
        except:
            traceback.print_exc()

    def start_timer(self):
        try:
            interval = self.spinBox.value() * 1000
            self.timer.start(interval)
            self.label.setStyleSheet("color:red;")
        except:
            traceback.print_exc()

    def stop_timer(self):
        try:
            self.timer.stop()
            self.label.setStyleSheet("color:black;")
        except:
            traceback.print_exc()

    def reload_time_string(self):
        try:
            time_string = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            self.label.setText(time_string)
        except:
            traceback.print_exc()

if __name__ == '__main__':
    authorization = None
    app = QApplication(sys.argv)
    main = Main()
    main.show()
    sys.exit(app.exec_())
