PyQt实现 计数器--快速掌握python开发桌面软件

1、引入相关模块
引入待会需要使用的qt模块。QtWidgets是界面布局和控件相关,QtCore是主要使用的类,比如以上的QTimer定时器类。
from PyQt5.QtWidgets import QWidget,QPushButton,\

QLabel,QVBoxLayout, QHBoxLayout,QApplication,QLCDNumber

from PyQt5.QtCore import QTimer
2、初始化界面布局和关联信号槽,设置窗口的标题和显示的位置​​​​​​​
class Form(QWidget):

def __init__(self):
    super().__init__()
    self.lable = QLabel("计时")
    self.timer = QTimer(self)
    self.lcd = QLCDNumber(self)
    self.startBtn = QPushButton('开始计时')
    self.stopBtn = QPushButton('暂停')
    self.startBtn.clicked.connect(self.startTimer)
    self.stopBtn.clicked.connect(self.stopTimer)
    vLayout = QVBoxLayout()
    hLayout = QHBoxLayout()
    vLayout.addWidget(self.lcd)
    hLayout.addWidget(self.startBtn)
    hLayout.addWidget(self.stopBtn)
    vLayout.addLayout(hLayout)
    self.setLayout(vLayout)
    self.timer.timeout.connect(self.showNum)
    self.setGeometry(300,300,400,300)
    self.setWindowTitle("Stopwatch")
    self.num = 0

这里把开始计数和暂停按钮通过水平布局放置,再和QLCDNumber进行垂直布局。然后通过connect设置对应的信号与槽的连接。
4、全部代码(拷贝即可运行)​​​​​​​
import sys
from PyQt5.QtWidgets import QWidget,QPushButton,\

QLabel,QVBoxLayout, 跟单网www.gendan5.com/QHBoxLayout,QApplication,QLCDNumber

from PyQt5.QtCore import QTimer
class Form(QWidget):

def __init__(self):
    super().__init__()
    self.lable = QLabel("计时")
    self.timer = QTimer(self)
    self.lcd = QLCDNumber(self)
    self.startBtn = QPushButton('开始计时')
    self.stopBtn = QPushButton('暂停')
    self.startBtn.clicked.connect(self.startTimer)
    self.stopBtn.clicked.connect(self.stopTimer)
    vLayout = QVBoxLayout()
    hLayout = QHBoxLayout()
    vLayout.addWidget(self.lcd)
    hLayout.addWidget(self.startBtn)
    hLayout.addWidget(self.stopBtn)
    vLayout.addLayout(hLayout)
    self.setLayout(vLayout)
    self.timer.timeout.connect(self.showNum)
    self.setGeometry(300,300,400,300)
    self.setWindowTitle("Stopwatch")
    self.num = 0
def showNum(self):
    self.lcd.display(self.num)
    self.num=self.num+1
    if(self.num==60):
        self.num=0
def startTimer(self):
    self.timer.start(1000)
def stopTimer(self):
    self.timer.stop()

if name == '__main__':

app = QApplication(sys.argv)
form = Form()
form.show()
sys.exit(app.exec_())

你可能感兴趣的:(python)