使用PyQt中的计时器更新标签

时间:2019-02-08 11:11:05

标签: python user-interface pyqt

我正在尝试使用单词列表每0.2秒更新一次QLabel。这是我当前的代码:

wordLabel = QLabel(window)
wordLabel.setFont(font)
wordLabel.setGeometry(120, 130, 200, 200)
wordLabel.hide()

def onTimeout():
    old = wordLabel.text()
    man = ["uncle", "hammer", "suit", "cigar", "beer", "boy",   "grandpa", "his", "motor", "guy", "razor", "mister","father", "blue", "football", "he", "brother", "tie", "tough", "man"]
    counter=0
    for item in man:
        counter=+1
        wordLabel.setText(str(man[counter]))
timer = QTimer()
timer.timeout.connect(onTimeout)
timer.start(2)

这将显示标签和仅一个单词,并且不会更新。我是一个初学者,所以任何提示都很棒。谢谢

1 个答案:

答案 0 :(得分:0)

尝试一下:

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class MyWin(QWidget):
    def __init__(self, man):
        super().__init__()

        self.man     = man
        self.counter = 0
        self.len_man = len(self.man)

        self.wordLabel = QLabel(self)
        self.wordLabel.setStyleSheet('font-size: 18pt; color: blue;')
        self.wordLabel.setGeometry(20, 20, 100, 50)

        timer = QTimer(self)
        timer.timeout.connect(self.onTimeout)
        timer.start(2000)

    def onTimeout(self):
        if self.counter >= self.len_man:
            self.counter = 0

        self.wordLabel.setText(str(self.man[self.counter]))
        self.counter += 1


man =  ["Hello", "Evans"] #["uncle", "hammer", "suit", "cigar", "beer", "boy",   "grandpa", "his", "motor", "guy", "razor", "mister","father", "blue", "football", "he", "brother", "tie", "tough", "man"]

if __name__ =="__main__":
    app = QApplication(sys.argv)
    app.setFont(QFontDatabase().font("Monospace", "Regular", 14))
    w = MyWin(man)
    w.show()
    sys.exit(app.exec())

enter image description here