1

在应用程序中有一个QButton和一个QLabel。在QLabelI put a QMoviein,显示一个GIF. 通过单击QButtonI want to change GIF,在 中定义的路径list

问题:应用程序只显示第一个 GIF。按钮似乎不起作用。我做错了什么?

但是:请不要更改代码的结构。例如,我想QLabel在子函数中定义,然后return从那里定义QLabel.

编码:

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

list = ['F:\\test1.gif', 'F:\\test2.gif', 'F:\\test3.gif', 'F:\\test4.gif']

class Window(QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.resize(600, 600)
        self.initUI()

    def initUI(self):
        self.btn = QPushButton("change", self)
        self.btn.clicked.connect(self.changeGIF)

        self.grid = QVBoxLayout()
        self.grid.addWidget(self.btn)
        self.grid.addWidget(self.changeGIF())
        self.grid.addStretch(1)

        self.setLayout(self.grid)


    def changeGIF(self):
        randomValue = list[random.randint(1, len(list)-1)]
        print(randomValue)

        self.lbl = QLabel()
        self.gif = QMovie(randomValue)
        self.lbl.setMovie(self.gif)
        self.gif.start()

        return self.lbl


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

谢谢您的帮助!

4

1 回答 1

2

由于QLabel将负责以随机方式显示 GIF,因此建议创建一个只处理该任务的类,在此小部件中,您必须有一个方法来更改QMovie.QLabel

list_of_gifs = ['F:\\test1.gif', 'F:\\test2.gif', 'F:\\test3.gif', 'F:\\test4.gif']

class GIFLabel(QLabel):
    def __init__(self, gifs, *args, **kwargs):
        QLabel.__init__(self, *args, **kwargs)
        self.mGifs = gifs
        self.changeGIF()

    def changeGIF(self):
        gif = random.choice(self.mGifs)
        movie = QMovie(gif)
        self.setMovie(movie)
        movie.start()

class Window(QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.resize(600, 600)
        self.initUI()

    def initUI(self):
        self.btn = QPushButton("change", self)
        self.label = GIFLabel(list_of_gifs, self)
        self.btn.clicked.connect(self.label.changeGIF)
        self.grid = QVBoxLayout(self)
        self.grid.addWidget(self.btn)
        self.grid.addWidget(self.label)
        self.grid.addStretch(1)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    MyApp = Window()
    MyApp.show()
    sys.exit(app.exec_())
于 2018-01-18T07:33:05.113 回答