凌的博客

您现在的位置是:首页  > 学无止境 > python

python

PyQt5 使用matplotlib.pylot画图

2019-08-30python0

2.jpg

import sys
import numpy as np
from PyQt5.QtWidgets import QMainWindow,QWidget,QApplication,QDesktopWidget,QPushButton,QVBoxLayout

import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FC




class QtDraw(QMainWindow):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # matlib PyQt5

        print("matplotlib")
        # 载入matplotlib
        self.fig = plt.Figure()
        self.canvas = FC(self.fig)
        self.btn_start = QPushButton("开始")
        self.btn_start.clicked.connect(self.draw)

        v = QVBoxLayout()
        v.addWidget(self.btn_start)
        v.addWidget(self.canvas)
        w = QWidget()
        w.setLayout(v)

        self.setCentralWidget(w)

        self.setGeometry(300,300,800,600)
        self.center()
        self.setWindowTitle("PyQt5 与 matplotlib")

    def draw(self):
        print("绘画开始")
        try:
            ax = self.fig.add_subplot(111)
            x = np.linspace(0,100,100)
            y = np.random.random(100)
            ax.cla() #删除原图,让画布上只有新的一次的图
            ax.plot(x,y)
            self.canvas.draw()

        except Exception as e:
            print(str(e))


    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())


if __name__ == "__main__":
    app = QApplication(sys.argv)
    draw = QtDraw()
    draw.show()
    sys.exit(app.exec_())


如果本文对您有所帮助,请支持下本站哦!!!^_^

文章评论

0条评论