Python QTimer 和图形用户界面 (GUI) 应用程序如何与 Qt 协同工作?

How Python QTimer and graphical user interface (GUI) applications with Qt works together?

我启动了计时器并以 1 秒的间隔连接到函数调用“read_file”。但是,GUI 界面不会出现。我不明白 Python QTimer 和 QT GUI 如何协同工作?我该怎么做才能弹出我的 GUI 页面并显示 ping 状态。如果有任何帮助,我将不胜感激。

import sys
from reachable_gui import *
import subprocess
import threading
import time
from PyQt5.QtCore import QTimer
import os

def signal(self):
    
    self.Button_Manual.clicked.connect(Manual)
    self.Button_Pdf.clicked.connect(Pdf)
    read_file(self)
   
def Manual():
    pass

def Pdf():
    pass
      
def read_file(self):
        {
    #read line by line IP and device from a file and pass it to ping()
    }
  timer = QtCore.QTimer()
  timer.timeout.connect(self.read_file)
  timer.setInterval(1000)
  timer.start()
        
def ping(self,IP,name):
    { 
    # ping the device and update GUI status.
    }
    
Ui_MainWindow.ping = ping
Ui_MainWindow.signal = signal
Ui_MainWindow.Manual = Manual
Ui_MainWindow.Pdf = Pdf
Ui_MainWindow.read_file = read_file

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    ui.signal()
    MainWindow.show()
    sys.exit(app.exec_())

我不知道这是否能帮助您解决问题,但这是如何多次使用 QTimer 到 运行 功能的示例。

但是如果函数 运行 更长,那么它可能会创建更长的间隔。

import sys
from PyQt5.QtCore import QTimer
from PyQt5 import QtWidgets
import datetime
#import time
   
def read_file():
    #time.sleep(2) # simulate long-running function
    
    current_time = datetime.datetime.now().strftime('%Y.%m.%d - %H:%M:%S')
    label.setText(current_time)
    
    print('current_time:', current_time)
    

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = QtWidgets.QMainWindow()
    
    # some GUI in window
    label = QtWidgets.QLabel(window, text='???')
    window.setCentralWidget(label)
    window.show()
    
    # timer which repate function `read_file` every 1000ms
    timer = QTimer()
    timer.timeout.connect(read_file)
    timer.setInterval(1000)
    timer.start()
    
    sys.exit(app.exec())