完整實例app
1 import sys 2 3 from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, \ 4 QPushButton 5 from PyQt5.QtGui import QIcon 6 7 from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas 8 from matplotlib.figure import Figure 9 import matplotlib.pyplot as plt 10 from PyQt5.QtCore import QTimer 11 import random 12 import numpy as np 13 from scipy import interpolate 14 15 16 class App(QMainWindow): 17 18 def __init__(self): 19 super().__init__() 20 self.left = 10 21 self.top = 10 22 self.title = '這裏能夠修改標題' 23 self.width = 640 24 self.height = 400 25 self.initUI() 26 27 def initUI(self): 28 self.setWindowTitle(self.title) 29 self.setGeometry(self.left, self.top, self.width, self.height) 30 31 m = PlotCanvas(self, width=5, height=4)#實例化一個畫布對象 32 m.move(0, 0) 33 34 button = QPushButton('這是一個按鈕', self) 35 button.setToolTip('This s an example button') 36 button.move(500, 0) 37 button.resize(140, 100) 38 button.clicked.connect(m.plot) 39 40 self.show() 41 42 43 class PlotCanvas(FigureCanvas): 44 45 def __init__(self, parent=None, width=5, height=4, dpi=100): 46 fig = Figure(figsize=(width, height), dpi=dpi) 47 self.axes = fig.add_subplot(111) 48 49 FigureCanvas.__init__(self, fig) 50 self.setParent(parent) 51 52 FigureCanvas.setSizePolicy(self, 53 QSizePolicy.Expanding, 54 QSizePolicy.Expanding) 55 FigureCanvas.updateGeometry(self) 56 self.init_plot()#打開App時能夠初始化圖片 57 #self.plot() 58 59 def plot(self): 60 61 timer = QTimer(self) 62 timer.timeout.connect(self.update_figure) 63 timer.start(100) 64 65 def init_plot(self): 66 x = [1, 2, 3, 4, 5, 6, 7, 8, 9] 67 y = [23, 21, 32, 13, 3, 132, 13, 3, 1] 68 self.axes.plot(x, y) 69 70 def update_figure(self): 71 x = np.linspace(0, 10, 10) 72 y = [random.randint(0, 10) for i in range(10)] 73 xx = np.linspace(0, 10) 74 f = interpolate.interp1d(x, y, 'quadratic') # 產生插值曲線的函數 75 yy = f(xx) 76 self.axes.cla() 77 self.axes.plot(x, y, 'o',xx,yy) 78 self.draw() 79 80 81 82 if __name__ == '__main__': 83 app = QApplication(sys.argv) 84 ex = App() 85 sys.exit(app.exec_()) 86 87 88 89 if __name__ == '__main__': 90 app = QApplication(sys.argv) 91 ex = App() 92 sys.exit(app.exec_())