Stack Overflow на русском Asked on December 9, 2021
Как сделать так, чтобы при запуске приложения включался секундомер,
который будет выводить часы, минуты и миллисекунды в label
?
И как сделать так, чтобы при нажатии pushButton
таймер останавливался
и время в label
оставалось?
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(733, 532)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(180, 389, 398, 86))
self.pushButton.setObjectName("pushButton")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(222, 195, 299, 46))
font = QtGui.QFont()
font.setPointSize(22)
font.setStyleStrategy(QtGui.QFont.PreferAntialias)
self.label.setFont(font)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "ОСТАНОВИТЬ ТАЙМЕР"))
self.label.setText(_translate("MainWindow", "00:00:00:000"))
class ExampleApp(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
if __name__=="__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
window = ExampleApp()
window.show()
app.exec_()
Вам надо изучить класс QTimer
https://doc.qt.io/qt-5/qtimer.html.
Формат строки результата посмотрите и выберите себе самостоятельно https://doc.qt.io/qt-5/qdatetime.html#YearRange-enum.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(733, 532)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(180, 389, 398, 86))
self.pushButton.setObjectName("pushButton")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(222, 195, 299, 46))
font = QtGui.QFont()
font.setPointSize(22)
font.setStyleStrategy(QtGui.QFont.PreferAntialias)
self.label.setFont(font)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "ОСТАНОВИТЬ ТАЙМЕР"))
self.label.setText(_translate("MainWindow", "00:00:00:000"))
class ExampleApp(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.setText("ЗАПУСТИТЬ ТАЙМЕР")
self.pushButton.clicked.connect(self.click_button)
self.timer = QtCore.QTimer(self)
self.timer.setInterval(1000)
self.timer.timeout.connect(self.displayTime)
def click_button(self):
if self.pushButton.text() == "ЗАПУСТИТЬ ТАЙМЕР":
self.timer.start()
self.pushButton.setText("ОСТАНОВИТЬ ТАЙМЕР")
else:
self.timer.stop()
self.pushButton.setText("ЗАПУСТИТЬ ТАЙМЕР")
def displayTime(self):
self.label.setText(QtCore.QDateTime.currentDateTime().toString())
self.label.adjustSize()
if __name__=="__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
window = ExampleApp()
window.show()
app.exec_()
Update
я имел ввиду после нажатия кнопки должен начинаться отчет миллисекунд и секунд как обычный секундомер
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(733, 532)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(180, 389, 398, 86))
self.pushButton.setObjectName("pushButton")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(222, 195, 299, 46))
font = QtGui.QFont()
font.setPointSize(22)
font.setStyleStrategy(QtGui.QFont.PreferAntialias)
self.label.setFont(font)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "ОСТАНОВИТЬ ТАЙМЕР"))
self.label.setText(_translate("MainWindow", "00:00:00:000"))
class ExampleApp(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.setText("ЗАПУСТИТЬ ТАЙМЕР")
self.pushButton.clicked.connect(self.click_button)
self.timer = QtCore.QTimer(self)
self.timer.setInterval(100) # +
self.timer.timeout.connect(self.displayTime)
def click_button(self):
if self.pushButton.text() == "ЗАПУСТИТЬ ТАЙМЕР":
self.timer.start()
self.pushButton.setText("ОСТАНОВИТЬ ТАЙМЕР")
else:
self.timer.stop()
self.pushButton.setText("ЗАПУСТИТЬ ТАЙМЕР")
def displayTime(self):
# self.label.setText(QtCore.QDateTime.currentDateTime().toString())
self.label.setText(QtCore.QDateTime.currentDateTime().toString('hh:mm:ss:zzz')) # +++
self.label.adjustSize()
if __name__=="__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
window = ExampleApp()
window.show()
app.exec_()
Update 2
извиняюсь, но мне надо надо сделать так чтоб label показывал секунды с нуля а не с текущего время на пк. Я не понимаю как это сделать
Я вам предложу все, что вам может пригодиться.
from PyQt5.QtWidgets import QGridLayout, QVBoxLayout, QPushButton, QRadioButton,
QSpinBox, QWidget, QLCDNumber, QLabel, QGroupBox, QHBoxLayout, QDialog
from PyQt5.QtCore import pyqtSignal,pyqtSlot,QTimer
import time
class Timer(QDialog):
timeout = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
self.time = 0
self.timeInterval = 1000 # По умолчанию секунды
self.timerUp = QTimer()
self.timerUp.setInterval(self.timeInterval)
self.timerUp.timeout.connect(self.updateUptime)
self.timerDown = QTimer()
self.timerDown.setInterval(self.timeInterval)
self.timerDown.timeout.connect(self.updateDowntime)
self.initUi()
self.buttonStart.clicked.connect(self.timerUp.start)
self.buttonStop.clicked.connect(self.timerUp.stop)
self.buttonReset.clicked.connect(self.reset)
self.buttonCountDown.clicked.connect(self.timerDown.start)
self.buttonStopAlarm.clicked.connect(self.timerDown.stop)
self.timeSpinBox.valueChanged.connect(self.settimer)
def initUi(self):
mainLayout = QVBoxLayout()
self.setLayout(mainLayout)
self.groupBox = QGroupBox(" Выбираем интервал ")
self.radioButton1 = QRadioButton("s")
self.radioButton1.toggled.connect(self.setUnit)
self.radioButton2 = QRadioButton("0.1s")
self.radioButton2.toggled.connect(self.setUnit)
self.radioButton3 = QRadioButton("0.01s")
self.radioButton3.toggled.connect(self.setUnit)
self.radioButton4 = QRadioButton("1ms")
self.radioButton4.toggled.connect(self.setUnit)
self.radioButton1.setChecked(True)
self.unitLayout = QHBoxLayout()
self.unitLayout.addWidget(self.radioButton1)
self.unitLayout.addWidget(self.radioButton2)
self.unitLayout.addWidget(self.radioButton3)
self.unitLayout.addWidget(self.radioButton4)
self.groupBox.setLayout(self.unitLayout)
mainLayout.addWidget(self.groupBox)
self.buttonStart = QPushButton(self.tr("start"))
mainLayout.addWidget(self.buttonStart)
self.buttonStop = QPushButton(self.tr("stop"))
mainLayout.addWidget(self.buttonStop)
self.timeViewer = QLCDNumber()
self.timeViewer.setFixedHeight(45)
mainLayout.addWidget(self.timeViewer)
self.timeForHuman = QLabel()
mainLayout.addWidget(self.timeForHuman)
self.buttonReset = QPushButton(self.tr("reset"))
mainLayout.addWidget(self.buttonReset)
self.timeSpinBox = QSpinBox()
self.timeSpinBox.setRange(0, 1000000000)
mainLayout.addWidget(self.timeSpinBox)
self.groupBoxCountDown = QGroupBox(" Обратный отсчет ")
countDown = QVBoxLayout()
self.buttonCountDown = QPushButton(self.tr("Cтарт"))
self.buttonStopAlarm = QPushButton(self.tr("Стоп"))
countDown.addWidget(self.buttonCountDown)
countDown.addWidget(self.buttonStopAlarm)
self.groupBoxCountDown.setLayout(countDown)
mainLayout.addWidget(self.groupBoxCountDown)
def setUnit(self):
if self.radioButton1.isChecked():
self.timeInterval = 1000
elif self.radioButton2.isChecked():
self.timeInterval = 100
elif self.radioButton3.isChecked():
self.timeInterval = 10
elif self.radioButton1.isChecked():
self.timeInterval = 1
self.timerUp.setInterval(self.timeInterval)
self.timerDown.setInterval(self.timeInterval)
def updateUptime(self):
self.time += 1
self.settimer(self.time)
def updateDowntime(self):
self.time =self.time-1
self.settimer(self.time)
if self.time <=0:
self.timeout.emit()
def settimer(self,int):
self.time=int
self.timeViewer.display(self.time)
if self.timeInterval ==1000:
self.timeForHuman.setText(
time.strftime('%H hour %M minute %S second', time.gmtime(self.time)))
elif self.timeInterval ==100:
self.timeForHuman.setText(
time.strftime('%H hour %M minute %S second', time.gmtime(self.time/10)))
elif self.timeInterval ==10:
self.timeForHuman.setText(
time.strftime('%H hour %M minute %S second', time.gmtime(self.time/100)))
elif self.timeInterval ==1:
self.timeForHuman.setText(
time.strftime('%H hour %M minute %S second', time.gmtime(self.time/1000)))
def reset(self):
self.time=0
self.settimer(self.time)
if __name__ == '__main__':
from PyQt5.QtWidgets import QApplication
import sys
app = QApplication(sys.argv)
timer = Timer()
def beep():
print('a')
timer.timeout.connect(beep)
timer.show()
sys.exit(app.exec_())
Answered by S. Nick on December 9, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP