使用QLabel在PyQt GUI中显示gif

时间:2018-11-03 18:50:00

标签: python pyqt pyqt4 qlabel

我试图在按下按钮后显示加载的gif。这是我目前拥有的代码

currentScale = Math.min(canvas.width/image.width, canvas.height/image.height);

我想在按下按钮后显示名为“ loading.gif”的gif。按下按钮后什么也没出现,我不确定如何正确显示gif。 gif与我创建的屏幕大小相同(240x320)。

1 个答案:

答案 0 :(得分:1)

问题在于QMovieLabel是gif_display中的局部变量,因此当函数完成运行时将被删除,因此解决方案是避免删除它。有2个选项:将其设为类的属性或使其成为窗口的子级,我将显示第二种方法,因为我认为这是您想要的方法:

import sys
from PyQt4 import QtCore, QtGui

class MainWindow (QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow,self).__init__(parent)
        self.setGeometry(50,50,240,320)
        self.home()

    def home(self):
        but = QtGui.QPushButton("Example", self) # Creates the brew coffee button
        but.clicked.connect(self.gif_display)
        but.resize(200,80)
        but.move(20,50)
        self.show()

    @QtCore.pyqtSlot()
    def gif_display(self):
        l = QMovieLabel('loading.gif', self)
        l.adjustSize()
        l.show()

class QMovieLabel(QtGui.QLabel):
    def __init__(self, fileName, parent=None):
        super(QMovieLabel, self).__init__(parent)
        m = QtGui.QMovie(fileName)
        self.setMovie(m)
        m.start()

    def setMovie(self, movie):
        super(QMovieLabel, self).setMovie(movie)
        s=movie.currentImage().size()
        self._movieWidth = s.width()
        self._movieHeight = s.height()

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = MainWindow()
    sys.exit(app.exec_())

if __name__ == '__main__':
    run()