返回

如何从菜单栏控制实时动画?但仅限于当前页面

python

如何从菜单栏控制实时动画,但仅控制位于前景的页面

摘要

本文档提供了分步指南,演示如何从菜单栏控制实时动画,但仅控制位于前景的页面。本文档涵盖了撰写博客文章所需的技能,包括文章撰写、SEO优化、文章标题创建和满足写作需求。

引言

在 Raspberry pi 4B 中使用 matplotlib 和 tkinter 进行工作。有三个不同的传感器读数实时显示。目标是从菜单栏中选择一个传感器,打开相应的页面。在页面中,将只显示一个空白图表。将从菜单中启动/停止读取,这将立即开始显示读数。还可以从菜单中停止动画。

遇到的问题

  1. 注意到动画在后台运行。不确定如何停止它。
  2. 不知道如何对菜单栏中的启动和停止选项进行编程以控制当前图表。
  3. 不确定如何修改函数 animate_graph 以读取调用它的帧。这似乎更像是一个简单的问题,但不知道应将什么参数传递给此函数。

方法

代码修改

我们修改了 animate_graph 函数以读取调用它的帧,并添加了用于控制动画的按钮。

def animate_graph(frame): #read the frame
    
    reading1,reading2 = (5-3) * np.random.random() + 3,(5-3) * np.random.random() + 3
    
    
    #append xs and ys with time and temp respectively
    x_s1.append(dt.datetime.now().strftime('%H:%M:%S'))
    y1_s1.append(reading1)
    y2_s1.append(reading2)
    
    #limit xs and ys to the last 10 seconds
    x_s1 = x_s1[-10:]
    y1_s1 = y1_s1[-10:]
    y2_s1 = y2_s1[-10:]
    
    #Draw x and y lists
    #y-axis for temperature
    color = 'tab:red'
    ax1_s1.clear()
    ln1= ax1_s1.plot(x_s1,y1_s1,color = color, linestyle = 'dashed', label = 'Read1')
    ax1_s1.tick_params(axis = 'y', labelcolor = color)
    
    #y-axis for relative humidity
    color = 'tab:blue'
    ax2_s1.clear()
    ln2 = ax2_s1.plot(x_s1,y2_s1,color = color,label = 'Read2')
    ax2_s1.tick_params(axis = 'y', labelcolor = color)

    #get different axes labels together
    lns = ln1+ln2 
    labs = [l.get_label() for l in lns]
    ax1_s1.legend(lns,labs,bbox_to_anchor = (0,1.02,1,0.102),loc = 3,ncol = 3,borderaxespad = 0)

    #x-axis label rotated to 45 degrees to avoid overlapping
    ax1_s1.tick_params(axis = 'x', labelrotation = 45)

GraphS1 页面中,我们添加了用于控制动画的按钮。

class GraphS1(tk.Frame):
    def __init__(self,parent,control):
        tk.Frame.__init__(self,parent)
        
        label = tk.Label(self,text = "Real-time Graph ",font = LARGE_FONT)
        label.pack()
        
        b1 = ttk.Button(self,text = "Go back to StartPage",
        command = lambda: control.show_frame(StartPage))
        b1.pack()

        b2 = ttk.Button(self,text = "Pause",
        command = lambda: anim.event_source.stop())
        b2.pack()

        b3 = ttk.Button(self,text = "Resume",
        command = lambda: anim.event_source.start())
        b3.pack()

问题和解决方案

1. 动画在后台运行

解决方案:修改 animate_graph 函数以读取调用它的帧。

2. 如何对菜单栏中的启动和停止选项进行编程以控制当前图表

解决方案:在 GraphS1 页面中添加用于控制动画的按钮。

3. 如何修改函数 animate_graph 以读取调用它的帧

解决方案:在 animate_graph 函数中添加一个参数以读取调用它的帧。

结论

通过这些代码修改,我们能够从菜单栏控制实时动画,但仅控制位于前景的页面。我们添加了用于控制动画的按钮,并修改了 animate_graph 函数以读取调用它的帧。

常见问题解答

1. 如何从菜单栏控制动画?

通过在菜单栏中添加启动和停止按钮来控制动画。

2. 如何只控制位于前景的页面的动画?

通过在位于前景的页面中添加控制动画的按钮来控制动画。

3. 如何修改函数 animate_graph 以读取调用它的帧?

animate_graph 函数中添加一个参数以读取调用它的帧。

4. 如何暂停动画?

使用暂停按钮暂停动画。

5. 如何恢复动画?

使用恢复按钮恢复动画。