1.使用:
import time
time.sleep(1) # 暂停一秒
会导致程序卡顿 !!!
2.可以使用 PyQt5 的 QTimer
类来实现定时器功能,以便实现实时的显示。这样可以避免阻塞主线程,让程序保持响应
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QTextEdit
from PyQt5.QtCore import QTimer
from io import StringIO
class OutputLogger(object):
def __init__(self, text_edit):
self.text_edit = text_edit
self.buffer = StringIO()
def write(self, message):
self.buffer.write(message)
cursor = self.text_edit.textCursor()
cursor.movePosition(cursor.End)
cursor.insertText(message)
self.text_edit.setTextCursor(cursor)
self.text_edit.ensureCursorVisible()
def flush(self):
pass
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('Redirect Output to QTextEdit')
# 创建一个文本框
self.text_edit = QTextEdit()
self.text_edit.setReadOnly(True)
# 创建一个按钮来触发输出
self.button = QPushButton('Click me', self)
self.button.clicked.connect(self.on_button_clicked)
# 设置布局
layout = QVBoxLayout()
layout.addWidget(self.text_edit)
layout.addWidget(self.button)
# 创建主窗口的中心部件
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
# 创建定时器,每秒触发一次,
# 它创建了一个新的QTimer对象,并将它赋值给了self.timer变量。这个QTimer对象用于触发定时事件。
self.timer = QTimer(self)
# ,将self.print_next_number方法与定时器的timeout信号关联起来。每当定时器超时时(即达到设定的时间间隔),它会发出timeout信号,这个信号会触发与之连接的槽函数,即self.print_next_number方法。
self.timer.timeout.connect(self.print_next_number)
def on_button_clicked(self):
# 将输出重定向到文本框
sys.stdout = OutputLogger(self.text_edit)
# 启动定时器
self.counter = 0
# self.timer.start(1000)启动了定时器,并设定了定时器的触发间隔为1000毫秒,即1秒。这样,定时器就会在1秒钟后开始触发timeout信号,并调用与之关联的self.print_next_number方法。
self.timer.start(1000) # 每秒触发一次
def print_next_number(self):
# 输出数字和文本
self.counter += 1
print(self.counter)
print('Hello, world!')
print('This is a test.')
# 输出完毕后停止定时器
if self.counter >= 1000:
self.timer.stop()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())