使用Python编写一个基于对话框的程序,定义两个线程,其功能均是实现从1计数到10000,其中一个线程间隔1秒,一个线程间隔0.5秒计数加1,将两个计数器计数结果显示在界面,并可以随时暂停计数
时间: 2024-06-01 08:11:18 浏览: 52
以下是一个基于PyQt5的示例程序:
```python
import sys
import time
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton
class CounterThread(QThread):
countChanged = pyqtSignal(int)
def __init__(self, interval):
super().__init__()
self.interval = interval
self.paused = False
self.counter = 0
def run(self):
while self.counter < 10000:
if not self.paused:
self.counter += 1
self.countChanged.emit(self.counter)
time.sleep(self.interval)
def pause(self):
self.paused = True
def resume(self):
self.paused = False
class CounterDialog(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('Counter Dialog')
self.resize(300, 200)
self.label1 = QLabel('Interval 1s: 0', self)
self.label2 = QLabel('Interval 0.5s: 0', self)
self.button1 = QPushButton('Pause 1s Counter', self)
self.button1.clicked.connect(self.pauseCounter1)
self.button2 = QPushButton('Pause 0.5s Counter', self)
self.button2.clicked.connect(self.pauseCounter2)
self.button3 = QPushButton('Resume Counters', self)
self.button3.clicked.connect(self.resumeCounters)
layout = QVBoxLayout()
layout.addWidget(self.label1)
layout.addWidget(self.label2)
layout.addWidget(self.button1)
layout.addWidget(self.button2)
layout.addWidget(self.button3)
self.setLayout(layout)
self.counterThread1 = CounterThread(1)
self.counterThread1.countChanged.connect(self.updateCounter1)
self.counterThread2 = CounterThread(0.5)
self.counterThread2.countChanged.connect(self.updateCounter2)
def pauseCounter1(self):
self.counterThread1.pause()
def pauseCounter2(self):
self.counterThread2.pause()
def resumeCounters(self):
self.counterThread1.resume()
self.counterThread2.resume()
def updateCounter1(self, count):
self.label1.setText(f'Interval 1s: {count}')
def updateCounter2(self, count):
self.label2.setText(f'Interval 0.5s: {count}')
def show(self):
self.counterThread1.start()
self.counterThread2.start()
super().show()
if __name__ == '__main__':
app = QApplication(sys.argv)
dialog = CounterDialog()
dialog.show()
sys.exit(app.exec_())
```
程序中定义了一个`CounterThread`类,继承自`QThread`,用来实现计数功能。`CounterThread`类有一个`countChanged`信号,用来在计数发生变化时发射信号。`CounterThread`类还有`pause()`和`resume()`方法,用来暂停和恢复计数。
程序中还定义了一个`CounterDialog`类,继承自`QWidget`,用来实现对话框界面。`CounterDialog`类有三个`QLabel`和三个`QPushButton`,用来显示计数结果和控制计数。`CounterDialog`类还创建了两个`CounterThread`实例,分别用来计数间隔1秒和0.5秒。
在`CounterDialog`的`show()`方法中,启动了两个`CounterThread`线程。
在程序中,通过调用`pause()`和`resume()`方法,可以暂停和恢复计数。`pauseCounter1()`和`pauseCounter2()`方法分别用来暂停间隔1秒和0.5秒的计数,`resumeCounters()`方法用来恢复计数。
程序的运行效果如下图所示:
![counter_dialog.png](https://cdn.jsdelivr.net/gh/krislinzhao/CDN/tuandui/2021-3-10/1615387845073-counter_dialog.png)
阅读全文