PyQt5:更新标签?

时间:2017-04-20 17:49:27

标签: python pyqt pyqt5 qlabel

我目前无法连续更新标签,我尝试了不同的方法但是没有任何反应或程序停止工作。我附上了部分代码。我也希望有人能够解释def retranslateUi的目的(self,MainWindow):

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("Tom")
        MainWindow.setWindowModality(QtCore.Qt.NonModal)
        MainWindow.resize(800, 600)
        MainWindow.setAutoFillBackground(False)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName("verticalLayout")
        self.Date = QtWidgets.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setPointSize(18)
        self.Date.setFont(font)
        self.Date.setAlignment(QtCore.Qt.AlignCenter)
        self.Date.setObjectName("Date")
        self.verticalLayout.addWidget(self.Date)
        self.Time = QtWidgets.QLabel(self.centralwidget)
        self.Time.setAlignment(QtCore.Qt.AlignCenter)
        self.Time.setObjectName("It is currently " + datetime.strptime(d, "%H:%M:%S").strftime( " %I:%M:%S %p"))
        self.verticalLayout.addWidget(self.Time)
        self.Weather = QtWidgets.QLabel(self.centralwidget)
        self.Weather.setAlignment(QtCore.Qt.AlignCenter)
        self.Weather.setWordWrap(False)
        self.Weather.setObjectName("Weather")
        self.verticalLayout.addWidget(self.Weather)
        spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.verticalLayout.addItem(spacerItem)
        spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.verticalLayout.addItem(spacerItem1)
        spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.verticalLayout.addItem(spacerItem2)
        spacerItem3 = QtWidgets.QSpacerItem(771, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.verticalLayout.addItem(spacerItem3)
        spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.verticalLayout.addItem(spacerItem4)
        spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.verticalLayout.addItem(spacerItem5)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)


    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("Tom", "Tom"))
        self.Date.setText(_translate("Tom", "Today is " + week_day +" the " + (ordinal(day)) + " of " + (month)))
        self.Time.setText(_translate("Tom", "It is currently " + datetime.strptime(d, "%H:%M:%S").strftime( " %I:%M:%S %p")))
        self.Weather.setText(_translate("Tom", "New York City " + str(ctemp) + "\xb0F " + string.capwords(status)))


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

我希望获得当前时间的标签能够不断更新,并且每隔5分钟就会调用天气api。非常感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

要实现代码,我们将执行以下操作:

  1. 更新我们使用计时器的时间。
  2. 要获取天气数据,我们使用pyowm库。
  3. 获取天气的任务可以阻止GUI的主线程,因此我们将创建一个Thread。
  4. 在线程中,我们将创建一个信号,用于存储天气信息并通过updateTemp插槽将其连接到主线程。
  5. class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
        def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent=parent)
            self.setupUi(self)
            timerTime = QtCore.QTimer(self)
            timerTime.timeout.connect(self.updateDate)
            timerTime.start(1000)
            self.pyowm = PyownThread(self)
            self.pyowm.tempSignal.connect(self.updateTemp)
            self.pyowm.start()
    
        def updateDate(self):
            date = QtCore.QDateTime.currentDateTime()
            self.Date.setText("Today is " + date.toString("ddd MMMM d yyyy"))
            self.Time.setText("It is currently " + date.toString("hh:mm:ss ap"))
    
        def updateTemp(self, temp):
            self.Weather.setText("New York City temperature:" + str(temp['temp']) + " \u00B0C")
    

    主题:

    class PyownThread(QtCore.QThread):
        tempSignal = QtCore.pyqtSignal(dict)
        def __init__(self, parent=None):
            super(PyownThread, self).__init__(parent=parent)
            self.owm = pyowm.OWM('1589dbcc0e9608e5b70f0ede23e757c8')
    
    
        def run(self):
            while True:
                observation = self.owm.weather_at_place('New York,us')
                w = observation.get_weather()
                ctemp = w.get_temperature('celsius')
                self.tempSignal.emit(ctemp)
                self.sleep(5*60)
    

    关于这个问题:可以准确解释def retranslateUi(self,MainWindow)的目的吗?

    这可以翻译成多种语言,例如,相同的代码可以用于说英语,西班牙语,德语等的听众。对于您的目的,没有必要。

    完整代码:

    from PyQt5 import QtWidgets, QtGui, QtCore
    import pyowm
    
    
    class Ui_MainWindow(object):
        def setupUi(self, MainWindow):
            MainWindow.setObjectName("Tom")
            MainWindow.setWindowModality(QtCore.Qt.NonModal)
            MainWindow.resize(800, 600)
            MainWindow.setAutoFillBackground(False)
            self.centralwidget = QtWidgets.QWidget(MainWindow)
            self.centralwidget.setObjectName("centralwidget")
            self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
            self.verticalLayout.setObjectName("verticalLayout")
            self.Date = QtWidgets.QLabel(self.centralwidget)
            font = QtGui.QFont()
            font.setPointSize(18)
            self.Date.setFont(font)
            self.Date.setAlignment(QtCore.Qt.AlignCenter)
            self.Date.setObjectName("Date")
            self.verticalLayout.addWidget(self.Date)
            self.Time = QtWidgets.QLabel(self.centralwidget)
    
            self.verticalLayout.addWidget(self.Time)
            self.Weather = QtWidgets.QLabel(self.centralwidget)
            self.Weather.setAlignment(QtCore.Qt.AlignCenter)
            self.Weather.setWordWrap(False)
            self.Weather.setObjectName("Weather")
            self.verticalLayout.addWidget(self.Weather)
            spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
            self.verticalLayout.addItem(spacerItem)
            spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
            self.verticalLayout.addItem(spacerItem1)
            spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
            self.verticalLayout.addItem(spacerItem2)
            spacerItem3 = QtWidgets.QSpacerItem(771, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
            self.verticalLayout.addItem(spacerItem3)
            spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
            self.verticalLayout.addItem(spacerItem4)
            spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
            self.verticalLayout.addItem(spacerItem5)
            MainWindow.setCentralWidget(self.centralwidget)
    
            self.retranslateUi(MainWindow)
            QtCore.QMetaObject.connectSlotsByName(MainWindow)
    
    
        def retranslateUi(self, MainWindow):
            _translate = QtCore.QCoreApplication.translate
            MainWindow.setWindowTitle(_translate("Tom", "Tom"))
            self.Date.setText(_translate("Tom", "Today is "))
            self.Time.setText(_translate("Tom", "It is currently "))
            self.Weather.setText(_translate("Tom", "New York City" ))
    
    
    class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
        def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent=parent)
            self.setupUi(self)
            timerTime = QtCore.QTimer(self)
            timerTime.timeout.connect(self.updateDate)
            timerTime.start(1000)
            self.pyowm = PyownThread(self)
            self.pyowm.tempSignal.connect(self.updateTemp)
            self.pyowm.start()
    
        def updateDate(self):
            date = QtCore.QDateTime.currentDateTime()
            self.Date.setText("Today is " + date.toString("ddd MMMM d yyyy"))
            self.Time.setText("It is currently " + date.toString("hh:mm:ss ap"))
    
        def updateTemp(self, temp):
            self.Weather.setText("New York City temperature:" + str(temp['temp']) + " \u00B0C")
    
    
    class PyownThread(QtCore.QThread):
        tempSignal = QtCore.pyqtSignal(dict)
        def __init__(self, parent=None):
            super(PyownThread, self).__init__(parent=parent)
            self.owm = pyowm.OWM('1589dbcc0e9608e5b70f0ede23e757c8') 
    
        def run(self):
            while True:
                observation = self.owm.weather_at_place('New York,us')
                w = observation.get_weather()
                ctemp = w.get_temperature('celsius')
                self.tempSignal.emit(ctemp)
                QtCore.QThread.sleep(5*60)
    
    
    
    if __name__ == "__main__":
        import sys
        app = QtWidgets.QApplication(sys.argv)
        w = MainWindow()
        w.show()
        sys.exit(app.exec_())
    

    enter image description here

答案 1 :(得分:1)

这是一个应该帮助你的小工作示例。 QTimer用于定期调用update_labelTime函数。

import sys
from PyQt5.QtCore import QTimer, QTime
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel

class MyApp(QMainWindow):
    def __init__(self):
        super(MyApp, self).__init__()

        self.labelTime = QLabel()
        self.update_labelTime()
        self.setCentralWidget(self.labelTime)

        self.timer = QTimer()
        self.timer.timeout.connect(self.update_labelTime)
        self.timer.start(1000) # repeat self.update_labelTime every 1 sec

    def update_labelTime(self):

        time_str = "Current time: {0}".format(QTime.currentTime().toString())
        self.labelTime.setText(time_str)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MyApp()
    window.show()
    sys.exit(app.exec_())

P.S。不要忘记更改timer.start电话

中的更新期