该图未使用matplotlib.animation

时间:2019-05-11 13:50:27

标签: python matplotlib tkinter raspberry-pi3 tkinter-canvas

我碰壁了,而且我无法在线找到有关同一问题的任何论坛帖子(至少在我搜索的几个小时内如此)。

作为序言;除了在过去的两个月中(慢慢地)在业余时间编写此代码,我对Python的了解很少。我很抱歉,如果我没有道理,我还不太了解Python命令的语法。还应该注意的是,这是在Raspberry Pi Model 3 B +上编码的。

我已经做了一些简短的故障排除,将动画函数的位置以及图形本身重新布置在应用程序类和“熔点/手动方法”类的内部和外部,但是我似乎无法对其进行动画处理。最多我只能只显示人物而没有动画。应该注意的是,相同的代码行在应用程序的先前迭代中工作,但是由于重新排列了类,因此该图不再更新。

from tkinter import *
from datetime import datetime
import time
from time import sleep
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.animation as animation
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
from matplotlib import pyplot as plt 
import csv
import tkinter
import numpy as np

class SampleApp(Tk):
    def __init__(self):
        Tk.__init__(self)
        self._frame = None
        self.fullscreen = True
        self.switch_frame(MeltPoint)

    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self.wm_attributes("-fullscreen", True)
        self.fullscreen = True
        self._frame = new_frame
        self._frame.grid(row=1, column=0)
        self.fst = Button(self, text="Toggle Fullscreen", command=self.fullscreen_toggle)
        self.fst.grid(row=0, column=0, rowspan=2, sticky='NW')

    def fullscreen_toggle(self):
        if self.fullscreen == False:
            self.wm_attributes("-fullscreen", True)
            self.fullscreen = True
        else:
            self.wm_attributes("-fullscreen", False)
            self.fullscreen = False

###########################################################

def animate(i):
    pullData = open("/home/pi/cpu_temp.txt","r").read()
    dataList = pullData.split('\n')
    xList = []
    yList = []
    for eachLine in dataList:
        if len(eachLine) > 1:
            x,y = eachLine.split(',')
            xList.append(float(x))
            yList.append(float(y))

    a.clear()
    a.plot(xList, yList)
    a.set_xlabel("Time[MM.SS]")
    a.set_ylabel("Temperature[°C]")

class Graph(Canvas):
    def __init__(self, master):
        Frame.__init__(self, master)            
        f = Figure(figsize=(9, 5), dpi=60)
        a = f.add_subplot(111)
        canvas = FigureCanvasTkAgg(f, self)
        canvas.draw()
        canvas.get_tk_widget().grid(row=0, column=0)
        ani = animation.FuncAnimation(f, animate, interval=100)

###########################################################


class MeltPoint(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        title = Label(self, text="Melting Point Determination").grid(row=0, column=1)       
        b1 = Button(self, height=4, width=12, text='Add Method', command=lambda: master.switch_frame(AddMethod)).grid(row=1, column=0, sticky='')
        b2 = Button(self, height=4, width=12,  text='Manual Method', command=lambda: master.switch_frame(ManMeth)).grid(row=2,column=0, sticky='')
        b3 = Button(self, height=4, width=12,  text='Recent Analysis/Results').grid(row=3,column=0, sticky='')
        b4 = Button(self, height=4, width=12,  text='Setup').grid(row=4,column=0, sticky='')
        b5 = Button(self, height=4, width=12,  text='Exit').grid(row=5,column=0, sticky='')
        tl = Frame(self, height=180, width=350, bd=1, relief=SUNKEN).grid(row=1, rowspan=3, column=1, sticky='')
###########################################################
        graph = Graph(self).grid(row=4, column=1, rowspan=3, sticky='')
###########################################################


class ManMeth(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        title = Label(self, text="Manual Method").grid(row=0, column=1)
        b1 = Button(self, height=4, width=12, text='Home', command=lambda: master.switch_frame(MeltPoint)).grid(row=1, column=0)
        b2 = Button(self, height=4, width=12,  text='Method Settings', command=lambda: master.switch_frame(AddMethod)).grid(row=2, rowspan=2, column=0)
        b3 = Button(self, height=4, width=12,  text='Start Analysis').grid(row=4,column=0)
        b4 = Button(self, height=4, width=12,  text='Data Handling').grid(row=5,column=0)
        b5 = Button(self, height=4, width=12,  text='Save Method').grid(row=6,column=0)    
        vidfrm = Frame(self, height=180, width=350, bd=1, relief=SUNKEN).grid(row=1, column=1, columnspan=2, rowspan=4)
###########################################################
        graph = Graph(self).grid(row=5, column=1, rowspan=3, sticky='')
###########################################################


if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

我希望图形从.txt文件更新,并读出CPU温度和时间以绘制在x和y轴上,目前仅显示静态图形。该图还应该在两个页面上更新(手动方法和熔点)。

1 个答案:

答案 0 :(得分:0)

要进行更新,我设法获取了图表以获取实时信息并进行更新,但是当您离开第一页时,该图表将停止更新(并且不会恢复)。为了达到这一阶段,我将对animate函数的调用添加到SampleApp()主循环中,从该图的类中删除了该图,并对其进行了独立绘制(全局?在此不确定术语),最后我将该调用添加到了画布.get_tk_widget()分配给每个框架类(“窗口/页面”)为MeltPoint和ManMeth。

再次对不起,如果我仍然挑剔我仍在学习的python术语,并且我并不能尽我所能描述我的更改!

如果有人能帮助我在两个页面上更新此图,我将非常感激! :)

from tkinter import *
from datetime import datetime
import time
from time import sleep
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.animation as animation
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
from matplotlib import pyplot as plt 
import csv
import tkinter
import numpy as np

class SampleApp(Tk):
    def __init__(self):
        Tk.__init__(self)
        self._frame = None
        self.fullscreen = True
        self.switch_frame(MeltPoint)

    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self.wm_attributes("-fullscreen", True)
        self.fullscreen = True
        self._frame = new_frame
        self._frame.grid(row=1, column=0)
        self.fst = Button(self, text="Toggle Fullscreen", command=self.fullscreen_toggle)
        self.fst.grid(row=0, column=0, rowspan=2, sticky='NW')

    def fullscreen_toggle(self):
        if self.fullscreen == False:
            self.wm_attributes("-fullscreen", True)
            self.fullscreen = True
        else:
            self.wm_attributes("-fullscreen", False)
            self.fullscreen = False

###########################################################

def animate(i):
    pullData = open("/home/pi/cpu_temp.txt","r").read()
    dataList = pullData.split('\n')
    xList = []
    yList = []
    for eachLine in dataList:
        if len(eachLine) > 1:
            x,y = eachLine.split(',')
            xList.append(float(x))
            yList.append(float(y))

    a.clear()
    a.plot(xList, yList)
    a.set_xlabel("Time[MM.SS]")
    a.set_ylabel("Temperature[°C]")



f = Figure(figsize=(9, 5), dpi=60)
a = f.add_subplot(111)

###########################################################


class MeltPoint(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        title = Label(self, text="Melting Point Determination").grid(row=0, column=1)       
        b1 = Button(self, height=4, width=12, text='Add Method', command=lambda: master.switch_frame(AddMethod)).grid(row=1, column=0, sticky='')
        b2 = Button(self, height=4, width=12,  text='Manual Method', command=lambda: master.switch_frame(ManMeth)).grid(row=2,column=0, sticky='')
        b3 = Button(self, height=4, width=12,  text='Recent Analysis/Results').grid(row=3,column=0, sticky='')
        b4 = Button(self, height=4, width=12,  text='Setup').grid(row=4,column=0, sticky='')
        b5 = Button(self, height=4, width=12,  text='Exit').grid(row=5,column=0, sticky='')
        tl = Frame(self, height=180, width=350, bd=1, relief=SUNKEN).grid(row=1, rowspan=3, column=1, sticky='')

###########################################################
        canvas = FigureCanvasTkAgg(f, self)
        canvas.draw()
        canvas.get_tk_widget().grid(row=4, column=1, rowspan=3, sticky='')
###########################################################


class ManMeth(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        title = Label(self, text="Manual Method").grid(row=0, column=1)
        b1 = Button(self, height=4, width=12, text='Home', command=lambda: master.switch_frame(MeltPoint)).grid(row=1, column=0)
        b2 = Button(self, height=4, width=12,  text='Method Settings', command=lambda: master.switch_frame(AddMethod)).grid(row=2, rowspan=2, column=0)
        b3 = Button(self, height=4, width=12,  text='Start Analysis').grid(row=4,column=0)
        b4 = Button(self, height=4, width=12,  text='Data Handling').grid(row=5,column=0)
        b5 = Button(self, height=4, width=12,  text='Save Method').grid(row=6,column=0)    
        vidfrm = Frame(self, height=180, width=350, bd=1, relief=SUNKEN).grid(row=1, column=1, columnspan=2, rowspan=4)
###########################################################
        canvas = FigureCanvasTkAgg(f, self)
        canvas.draw()
        canvas.get_tk_widget().grid(row=5, column=1, rowspan=3, sticky='')
###########################################################



if __name__ == "__main__":
    app = SampleApp()
    ani = animation.FuncAnimation(f, animate, interval=100)
    app.mainloop()