我如何在PyQt5中重新加载新的动画gif文件?
我想做什么:
以下是我为尝试此操作而设置的基本代码,但是单击按钮进行刷新不起作用:
import sys
from PyQt5.QtCore import Qt, QByteArray, QSettings, QTimer, pyqtSlot
from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QSizePolicy, QVBoxLayout, QAction, QPushButton
from PyQt5.QtGui import QMovie
class GifPlayer(QWidget):
def __init__(self, title, parent=None):
QWidget.__init__(self, parent)
self.movie = QMovie("test.gif", QByteArray(), self)
size = self.movie.scaledSize()
self.setGeometry(200, 200, size.width(), size.height())
self.setWindowTitle(title)
self.movie_screen = QLabel()
self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.movie_screen.setAlignment(Qt.AlignCenter)
main_layout = QVBoxLayout()
main_layout.addWidget(self.movie_screen)
self.setLayout(main_layout)
self.movie.setCacheMode(QMovie.CacheAll)
self.movie_screen.setMovie(self.movie)
self.movie.start()
self.movie.loopCount()
button = QPushButton('refresh gif', self)
button.setToolTip('This is an example button')
button.move(10,10)
button.clicked.connect(self.on_click)
@pyqtSlot()
def on_click(self):
self.movie_screen.setMovie(self.movie)
print("done")
if __name__ == "__main__":
app = QApplication(sys.argv)
player = GifPlayer("update this gif")
player.show()
sys.exit(app.exec_())
答案 0 :(得分:1)
事实证明这是一个非常简单的解决方案。错误是试图只刷新movie_screen而不是电影本身。只需再次设置QMovie文件,让movie_screen重新显示它,然后启动电影。这是更正后的代码:
gifFile = "test.gif"
class GifPlayer(QWidget):
def __init__(self, title, gifFile, parent=None):
QWidget.__init__(self, parent)
self.movie = QMovie(gifFile, QByteArray(), self)
size = self.movie.scaledSize()
self.setGeometry(200, 200, size.width(), size.height())
self.setWindowTitle(title)
self.movie_screen = QLabel()
self.movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.movie_screen.setAlignment(Qt.AlignCenter)
main_layout = QVBoxLayout()
main_layout.addWidget(self.movie_screen)
self.setLayout(main_layout)
self.movie.setCacheMode(QMovie.CacheAll)
self.movie_screen.setMovie(self.movie)
self.movie.start()
self.movie.loopCount()
button = QPushButton('refresh gif', self)
button.setToolTip('This is an example button')
button.move(10,10)
button.clicked.connect(self.on_click)
@pyqtSlot()
def on_click(self):
self.movie = QMovie(gifFile,QByteArray(), self)
self.movie_screen.setMovie(self.movie)
self.movie.start()
print("done")
if __name__ == "__main__":
app = QApplication(sys.argv)
player = GifPlayer("update this gif", gifFile)
player.show()
sys.exit(app.exec_())
on_click方法主要是需要更改的方法。