本範例描述物件導向的來龍去脈,更用近來火紅的 Pokemon 進行解說
MainWindow.py
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QGridLayout, QLabel
from Eve import Eve
from ui.ui_mainwindow import Ui_MainWindow
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.btn.clicked.connect(self.btn_click)
self.layout=QGridLayout(self.frame)
self.x=0
self.y=0
def btn_click(self):
eve=Eve()
self.layout.addWidget(eve,self.y, self.x)
self.x=(self.x+1)%5
if self.x==0:self.y+=1
if __name__=='__main__':
app=QApplication(sys.argv)
frame=MainWindow()
frame.showMaximized()
app.exec()
Eve.py
import random
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QLabel
class EveThread(QThread):
callback= pyqtSignal(int)
def __init__(self, delay=100, parent=None):
super().__init__(parent)
self.runFlag = True
self.index=0
self.delay=delay
def __del__(self):
self.runFlag=False
self.wait()
def run(self):
while self.runFlag:
self.callback.emit(self.index)
self.index=(self.index+1)%36
QThread.msleep(self.delay)
class Eve(QLabel):
def __init__(self, parent=None):
super().__init__(parent)
self.setPixmap(QPixmap('eve/frame_01.png'))
self.pix=[]
for i in range(1, 37):
s=str(i).zfill(2)
self.pix.append(QPixmap(f'eve/frame_{s}.png'))
self.thread=EveThread(random.randint(10,100))
self.thread.callback.connect(self.refresh)
self.thread.start()
def refresh(self, index):
self.setPixmap(self.pix[index])
