Pythontkinter库将matplotlib图表显⽰在GUI窗⼝上,并实时更新刷
新数据
代码
1'''
2使⽤matplotlib创建图表,并显⽰在tk窗⼝
3'''
4import matplotlib.pyplot as plt
5from matplotlib.pylab import mpl
6from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
7import tkinter as tk
8import numpy as np
9import time,sys
10import threading
11
Params['font.sans-serif'] = ['SimHei'] # 中⽂显⽰
Params['axes.unicode_minus'] = False # 负号显⽰
14
15global win
16global tempGraphLabel, tempData, runFlag
17 runFlag = True
18 tempData = []
19
20'''
21图表类,定义时参数root为⽗控件
22'''
23class tempGraph():
24def__init__(self, root):
25 = root # 主窗体
26 self.canvas = tk.Canvas() # 创建⼀块显⽰图形的画布
27 self.figure = ate_matplotlib() # 返回matplotlib所画图形的figure对象
28 self.showGraphIn(self.figure) # 将figure显⽰在tkinter窗体上⾯
29
30'''⽣成fig'''
31def create_matplotlib(self):
32# 创建绘图对象f
33 f = plt.figure(num=2, figsize=(16, 8), dpi=100, edgecolor='green', frameon=True)
34# 创建⼀副⼦图
35 self.fig11 = plt.subplot(1, 1, 1)
36 self.line11, = self.fig11.plot([], [])
37
38def setLabel(fig, title, titleColor="red"):
39 fig.set_title(title+"温度曲线", color=titleColor) # 设置标题
40 fig.set_xlabel('时间[s]') # 设置x轴标签
41 fig.set_ylabel("温度[℃]") # 设置y轴标签
42 setLabel(self.fig11, "设备1")
43# fig1.set_yticks([-1, -1 / 2, 0, 1 / 2, 1]) # 设置坐标轴刻度
44 f.tight_layout() # ⾃动紧凑布局
45return f
46
47'''把fig显⽰到tkinter'''
48def showGraphIn(self, figure):
49# 把绘制的图形显⽰到tkinter窗⼝上
50 self.canvas = FigureCanvasTkAgg(figure, )
51 self.canvas.draw() # 以前的版本使⽤show()⽅法,matplotlib 2.2之后不再推荐show()⽤draw代替,但是⽤show不会报错,会显⽰警告
52 _tk_widget().pack(side=tk.TOP) #, fill=tk.BOTH, expand=1
53
54# 把matplotlib绘制图形的导航⼯具栏显⽰到tkinter窗⼝上
55 toolbar = NavigationToolbar2Tk(self.canvas,
56 ) # matplotlib 2.2版本之后推荐使⽤NavigationToolbar2Tk,若使⽤NavigationToolbar2TkAgg会警告
57 toolbar.update()
58 self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
59
60'''更新fig'''
61def updateMeltGraph(self, meltData):
62 x = [i for i in range(len(meltData))]
63 self.line11.set_xdata(x) # x轴也必须更新
64 self.line11.set_ydata(meltData) # 更新y轴数据
65# 更新x数据,但未更新绘图范围。当我把新数据放在绘图上时,它完全超出了范围。解决办法是增加:
66 lim()
67 self.fig11.autoscale_view()
68 plt.draw()
69# self.canvas.draw_idle()
70'''
71更新数据,在次线程中运⾏
72'''
73def updataData():
74global tempData,runFlag
75while runFlag:
76 tempData.append(5)
77 time.sleep(1)
78'''
79更新窗⼝
80'''
81def updateWindow():
82global win
83global tempGraphLabel, tempData, runFlag
84if runFlag:
85 tempGraphLabel.updateMeltGraph(tempData)
86 win.after(1000, updateWindow) # 1000ms更新画布
87'''
88关闭窗⼝触发函数,关闭S7连接,置位flag
89'''
90def closeWindow():
91global runFlag
92 runFlag = False
93 it()
94'''
95创建控件
96'''
97def createGUI():
98global win
99 win = tk.Tk()
100 displayWidth = win.winfo_screenwidth() # 获取屏幕宽度
101 displayHeight = win.winfo_screenheight()
102 winWidth, winHeight = displayWidth, displayHeight - 70
103 winX, winY = -8, 0
104# winX, winY = int((displayWidth - winWidth) /
105# 2), int((displayHeight - winHeight - 70) / 2)
106 win.title("窗⼝标题")
107 ry(
108'%dx%d-%d+%d' %
109 (winWidth,
110 winHeight,
111 winX, winY)) # %dx%d宽度x ⾼度+横向偏移量(距左边)+纵向偏移量(距上边) 112# sizable(0, 0) # 不使能最⼤化
113 win.protocol("WM_DELETE_WINDOW", closeWindow)
114# win.iconbitmap(r'resource/images/motor.ico') # 窗⼝图标
115
116 graphFrame = tk.Frame(win) # 创建图表控件
117 graphFrame.place(x=0, y=0)
118global tempGraphLabel
119 tempGraphLabel = tempGraph(graphFrame)
120
121 recv_data = threading.Thread(target=updataData) # 开启线程
matplotlib中subplot122 recv_data.start()
123
124 updateWindow() # 更新画布
125 win.mainloop()
126
127if__name__ == '__main__':
128 createGUI()
实现效果
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论