python - Python QTimer 和带有 Qt 的图形用户界面 (GUI) 应用程序如何协同工作?
问题描述
我启动了计时器并以 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())
推荐阅读
- python - Argparse 中的可选参数
- python - 如何用python点击图像的第n个像素(不是你想的)
- sequelize.js - Sequelize ORM:在和运算符内部创建一个 OR 运算符
- swiftui - 带有适合内容的列的 SwiftUI 网格?
- python - 无法在函数python中传递列表和字典
- google-sheets - Google 表格上的 IMPORTHTML 返回 #N/A 错误,但仅在一个文档中
- javascript - Highcharts - Xrange 图表事件问题
- python - 没有名为“_ctypes”的模块
- python - Vs Code 在每个程序中都显示语法错误
- ionic-framework - 离子滑块在 ModalController ionic 4 中不起作用