点击按钮获取spinBox的值并每秒减一
时间: 2023-10-25 13:04:55 浏览: 38
以下是一个示例代码,可以实现获取spinBox的值并每秒减一的功能。
```python
from PyQt5.QtWidgets import QApplication, QWidget, QSpinBox, QLabel, QPushButton
from PyQt5.QtCore import QTimer
class MainWindow(QWidget):
def __init__(self):
super().__init__()
# 创建一个SpinBox
self.spinBox = QSpinBox(self)
self.spinBox.setGeometry(50, 50, 100, 30)
self.spinBox.setMinimum(0)
self.spinBox.setMaximum(100)
# 创建一个标签,用于显示spinBox的值
self.label = QLabel(self)
self.label.setGeometry(50, 100, 100, 30)
# 创建一个按钮,用于开始计时
self.button = QPushButton('Start', self)
self.button.setGeometry(50, 150, 100, 30)
self.button.clicked.connect(self.start_timer)
# 创建一个计时器,每秒钟触发一次
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_label)
# 初始化计数器
self.count = 0
def start_timer(self):
# 获取spinBox的值
value = self.spinBox.value()
# 设置倒计时的计数器
self.count = value
# 开始计时器
self.timer.start(1000)
def update_label(self):
if self.count > 0:
# 更新标签的显示
self.label.setText(str(self.count))
# 计数器减一
self.count -= 1
else:
# 停止计时器
self.timer.stop()
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
```
这个示例代码中,我们创建了一个SpinBox、一个标签和一个按钮。当用户点击按钮时,我们获取SpinBox的值,并将其赋值给一个计数器。然后我们启动一个计时器,每秒钟触发一次,计时器的回调函数会更新标签的显示,并将计数器减一。当计数器减为零时,计时器会停止。