我的代码没有更新,为什么?

2024-04-20 13:10:05 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能帮我写代码吗

根据我的温度传感器读数,从matplotlib更新tkinter上的图表不是实时的。我认为它不知何故不是从FuncAnimation更新的。我是新手,正在努力学习如何做

from tkinter import * 
from matplotlib.figure import Figure 
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,  
NavigationToolbar2Tk) 
from tkinter import *           #Tkinter Library/ install Tkinter - Python 3. sudo apt-get install python3-tk
import PIL                      #PIL - Image library
from PIL import Image           #PIL - Image library
import tkinter as tk            #Tkinter Library
import threading                #For running mulitple threads(task,fucntiom calls) 
import tkinter.font             #Tkinter font library
import adafruit_dht             #DHT22 temp/hum sensor library
import time                     #Timing
import board                    #RPi4 board pins schematic(D4 pin must be active for DHT22 sensor)
import random
import gaugelib
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# plot function is created for  
# plotting the graph in  
# tkinter window 
win = tk.Tk()
aDHTDevice = adafruit_dht.DHT22(board.D4)

# Creating tkinter window
fig = Figure(figsize = (8,8), dpi = 100)

    # Plotting the graph inside the Figure
a = fig.add_subplot(1,1,1)
xs = []
ys = []

def animate(i, xs, ys):

    temp_c = aDHTDevice.temperature
    xs.append(dt.datetime.now().strftime('%H:%M:%S.%f'))
    ys.append(temp_c)
    xs = xs[-20]
    ys = ys[-20]
    a.clear()
    a.plot(xs, ys)
    time.sleep(1)

a.set_xlabel("Marks")
a.set_ylabel("Students")
a.set_title("Graph_Tk")
a.grid()

# Creating Canvas
canv = FigureCanvasTkAgg(fig, master = win)
canv.draw()

get_widz = canv.get_tk_widget()
get_widz.pack()

win.attributes("-fullscreen",True)             #Fullscreen when executed 
win.bind("<1>",exit)                           #Mouse click to exit
def exit():                                     #Exit fullscreen
    win.quit() 
ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys), interval=2000)
win.mainloop()