当前位置:   article > 正文

pyqt5实现定时的显示:_pyqt 按下按钮开始定时出现

pyqt 按下按钮开始定时出现

1.使用:
import time
time.sleep(1) # 暂停一秒
会导致程序卡顿 !!!

2.可以使用 PyQt5QTimer 类来实现定时器功能,以便实现实时的显示。这样可以避免阻塞主线程,让程序保持响应

  1. import sys
  2. from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QTextEdit
  3. from PyQt5.QtCore import QTimer
  4. from io import StringIO
  5. class OutputLogger(object):
  6. def __init__(self, text_edit):
  7. self.text_edit = text_edit
  8. self.buffer = StringIO()
  9. def write(self, message):
  10. self.buffer.write(message)
  11. cursor = self.text_edit.textCursor()
  12. cursor.movePosition(cursor.End)
  13. cursor.insertText(message)
  14. self.text_edit.setTextCursor(cursor)
  15. self.text_edit.ensureCursorVisible()
  16. def flush(self):
  17. pass
  18. class MyWindow(QMainWindow):
  19. def __init__(self):
  20. super().__init__()
  21. self.initUI()
  22. def initUI(self):
  23. self.setWindowTitle('Redirect Output to QTextEdit')
  24. # 创建一个文本框
  25. self.text_edit = QTextEdit()
  26. self.text_edit.setReadOnly(True)
  27. # 创建一个按钮来触发输出
  28. self.button = QPushButton('Click me', self)
  29. self.button.clicked.connect(self.on_button_clicked)
  30. # 设置布局
  31. layout = QVBoxLayout()
  32. layout.addWidget(self.text_edit)
  33. layout.addWidget(self.button)
  34. # 创建主窗口的中心部件
  35. central_widget = QWidget()
  36. central_widget.setLayout(layout)
  37. self.setCentralWidget(central_widget)
  38. # 创建定时器,每秒触发一次,
  39. # 它创建了一个新的QTimer对象,并将它赋值给了self.timer变量。这个QTimer对象用于触发定时事件。
  40. self.timer = QTimer(self)
  41. # ,将self.print_next_number方法与定时器的timeout信号关联起来。每当定时器超时时(即达到设定的时间间隔),它会发出timeout信号,这个信号会触发与之连接的槽函数,即self.print_next_number方法。
  42. self.timer.timeout.connect(self.print_next_number)
  43. def on_button_clicked(self):
  44. # 将输出重定向到文本框
  45. sys.stdout = OutputLogger(self.text_edit)
  46. # 启动定时器
  47. self.counter = 0
  48. # self.timer.start(1000)启动了定时器,并设定了定时器的触发间隔为1000毫秒,即1秒。这样,定时器就会在1秒钟后开始触发timeout信号,并调用与之关联的self.print_next_number方法。
  49. self.timer.start(1000) # 每秒触发一次
  50. def print_next_number(self):
  51. # 输出数字和文本
  52. self.counter += 1
  53. print(self.counter)
  54. print('Hello, world!')
  55. print('This is a test.')
  56. # 输出完毕后停止定时器
  57. if self.counter >= 1000:
  58. self.timer.stop()
  59. if __name__ == '__main__':
  60. app = QApplication(sys.argv)
  61. window = MyWindow()
  62. window.show()
  63. sys.exit(app.exec_())

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/888289
推荐阅读
相关标签
  

闽ICP备14008679号