Tkinter wind中的python实时绘图

2024-09-29 17:24:26 发布

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

我想在一个基于时间的绘图中绘制传感器日期,它应该嵌入到Tkinter窗口中。目前我只想画出y1List和xList。在

到目前为止,我还没有找到一个针对我的特定用例的stackoverflow解决方案。在

我的代码:

import datetime                 # für Datum/Uhrzeit
from tkinter import *           # für GUI
import numpy as np
import matplotlib as mpl
import matplotlib.backends.tkagg as tkagg
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt


#Animation function
def animate(ax,xList,y1List,y2List):
    time = datetime.datetime.now().strftime("%H:%M:%S")
    lb_Time.config(text=time)
    lb_Time['text'] = time
    xList.append(time)
#   Replace sample data below my real data...
    y1List.append(np.sin(len(xList)))
    y2List.append(2*np.sin(len(xList)))
    # Limit x and y lists to 20 items
    xList = xList[-20:]
    y1List = y1List[-20:]
    y2List = y2List[-20:]
    line, = ax.plot_date(mpl.dates.datestr2num(xList), y1List)
    plt.show()
    fenster.after(1000,animate,ax,xList,y1List,y2List)


fenster = Tk()
fenster.title("Monitoring")
fenster.geometry("450x400")
lb_Time = Label(fenster)
exit_button = Button(fenster, text="Beenden", command=fenster.destroy, fg="red")    
lb_Time.grid(row=2, column=0,pady=20)

xList = []
y1List =[]
y2List = []

fig = plt.Figure(figsize=(2, 2))
canvas = FigureCanvasTkAgg(fig, master=fenster)
canvas.get_tk_widget().grid(row=3,column=1,pady=20)

ax = fig.add_subplot(111)
line, = ax.plot_date(xList, y1List)
animate(ax,xList,y1List,y2List)

fenster.mainloop()

我的问题是,绘图只是静态的,在y值为34时只绘制1个点。为什么不每1秒更新一次,为什么是34秒(就像我用窦房结?在


Tags: importdatetimetimematplotlibasnppltax
2条回答

我已经用这个代码做到了

...

from matplotlib.animation import FuncAnimation

...

_ANIM_INTERVAL = 1000  # Milliseconds.


def animate(counter: int) -> None:
    """Refresh graph.

    :param counter: Function call counter (2 times for 0!!!).
    """
    ...

...

_ = FuncAnimation(fig, animate, interval=_ANIM_INTERVAL)
show(fig)

吉咪

mainloop是一个阻塞语句,也就是说,当它遇到它时,现在将运行更多的代码。可以通过在mainloop之后添加print语句来验证这一点。我不太熟悉tkinter的内部工作,但使用本机matplotlib可以轻松编写动画函数:

import numpy as np, matplotlib.pyplot as plt
fig, ax = plt.subplots()
# dummy data
N      = 100
buffer = np.zeros((N, 2))
p = ax.plot(*buffer.T, marker = '.')[0] # get plot object
while True:
    for idx in range(N):
        buffer[idx, :] = np.random.rand(buffer.shape[1])
        p.set_data(*buffer.T)
        # recompute data limits
        ax.relim()
        ax.axes.autoscale_view(True, True, True)

        # update figure; flush events
        fig.canvas.draw()
        fig.canvas.flush_events()

相关问题 更多 >

    热门问题