pyqt5与matplotlib的完美结合实例

时间:2022-10-30 19:20:30

具体用到了matplotlib.backends.backend_qt5agg.figurecanvasqtagg

直接上代码(这里给出的只是一个简单的框架,告诉你怎么去写):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# -*- coding: utf-8 -*-
'''
todo:lqd
'''
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import figurecanvasqtagg as fc
from pyqt5.qtwidgets import qapplication, qpushbutton, qmainwindow, qvboxlayout, qwidget
 
 
class qtdraw(qmainwindow):
  flag_btn_start = true
 
  def __init__(self):
    super(qtdraw, self).__init__()
    self.init_ui()
 
  def init_ui(self):
    self.resize(800, 600)
    self.setwindowtitle('pyqt5 draw')
 
    # todo:这里是结合的关键
    self.fig = plt.figure()
    self.canvas = fc(self.fig)
    self.btn_start = qpushbutton(self)
    self.btn_start.settext('draw')
    self.btn_start.clicked.connect(self.slot_btn_start)
 
    widget = qwidget()
    layout = qvboxlayout()
    layout.addwidget(self.canvas)
    layout.addwidget(self.btn_start)
    widget.setlayout(layout)
    self.setcentralwidget(widget)
 
  def slot_btn_start(self):
    try:
      ax = self.fig.add_subplot(111)
      x = np.linspace(0, 100, 100)
      y = np.random.random(100)
      ax.cla() # todo:删除原图,让画布上只有新的一次的图
      ax.plot(x, y)
      self.canvas.draw() # todo:这里开始绘制
    except exception as e:
      print(e)
 
 
def ui_main():
  app = qapplication(sys.argv)
  w = qtdraw()
  w.show()
  sys.exit(app.exec_())
 
 
if __name__ == '__main__':
  ui_main()

以上这篇pyqt5与matplotlib的完美结合实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/shangxiaqiusuo1/article/details/90044849