【发布时间】:2020-04-15 18:48:03
【问题描述】:
以下代码是我项目的简化版本,它可以运行和绘制动画,但我必须在动画中添加blit=true 以加快速度(我原来的 UI 要复杂得多,速度慢得多)。我知道动画函数必须返回一系列 Artist 对象。我的subplot_2 中的艺术家对象是什么?我试过subplot_2,a,f,它们都不起作用。非常感谢
from multiprocessing import Process
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
##, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import style
import tkinter as tk
from tkinter import ttk
from tkinter import *
import matplotlib.pyplot as plt
import numpy as np
f = Figure(figsize=(6,6), dpi=100)
subplot_1 = f.add_subplot(211)
subplot_2 = f.add_subplot(212)
LARGE_FONT= ("Verdana", 12)
style.use("ggplot")
def animate(i):
time = np.random.rand(2, 25)
data = np.random.rand(2, 25)
a = subplot_2.scatter(time,data,c='blue',s=2)
#return a
class home(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Graph ")
self.geometry("1000x1000")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
F=Graph
frame=Graph(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(Graph)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
def get_frame(self, frame_class):
return self.frames[frame_class]
##
class Graph(tk.Frame):
def __init__(self, parent, controller):
global canvas
tk.Frame.__init__(self, parent)
label = tk.Label(self, text=" ", font=LARGE_FONT)
label.pack(pady=120,padx=10)
collectbtn=Button(self,text='collect',command=self.clickstart)
collectbtn.place(x=200,y=100)
canvas = FigureCanvasTkAgg(f, self)
## canvas.draw()
canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
def clickstart(self):
animate(0)
#aniplot_photon = animation.FuncAnimation(f, animate, blit=True,interval=100)
aniplot_photon = animation.FuncAnimation(f, animate, interval=100)
canvas.draw()
app = home()
app.mainloop()
更新:
感谢威廉的回答,它有效。但是,我还有其他问题,如果这个子图包含许多曲线"subplot_2.scatter(x1..),subplot_2.scatter(x2..),subplot_2.scatter(x3..),subplot_2.scatter(x1..)...",或者一些子图是从不同的线程更新的(制作对象并将它们全局化?),那么很难将所有曲线放入返回列表中。但是,我为上面列出的问题找到了一个简单的解决方案,我可以只使用return [subplot_2],它会更新 subplot_2 内的所有图,但是坐标(x 刻度)会丢失(运行,你会看到)。当我使用return [suplot_2] 时,有没有一种简单的方法可以保持坐标?
def animate(i):
time = np.random.rand(2, 25)
data = np.random.rand(2, 25)
a = subplot_2.scatter(time,data,c='blue',s=2)
return [subplot_2]
【问题讨论】:
标签: python-3.x matplotlib animation tkinter