我试着用matplotlib动画函数更新两个TKinter“页面”,每个页面都有不同的绘图。
问题是只有一页正确地显示了情节。
代码如下:
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
import Tkinter as tk
import ttk
a = Figure(figsize=(4,4))
plot_a = a.add_subplot(111)
b = Figure(figsize=(4,4))
plot_b = b.add_subplot(111)
x = [1,2,3,4,5]
y_a = [1,4,9,16,25]
y_b = [25,16,9,4,1]
def updateGraphs(i):
plot_a.clear()
plot_a.plot(x,y_a)
plot_b.clear()
plot_b.plot(x,y_b)
class TransientAnalysis(tk.Tk):
def __init__(self,*args,**kwargs):
tk.Tk.__init__(self,*args,**kwargs)
tk.Tk.wm_title(self, "Transient Analysis GUI: v1.0")
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 = {}
for F in ( GraphPageA, GraphPageB):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(GraphPageA)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class GraphPageA(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
button1 = ttk.Button(self, text="Show Graph B",
command = lambda: controller.show_frame(GraphPageB))
button1.grid(row=1, column=0,pady=20,padx=10, sticky='w')
canvasA = FigureCanvasTkAgg(a, self)
canvasA.show()
canvasA.get_tk_widget().grid(row=1, column=1, pady=20,padx=10, sticky='nsew')
class GraphPageB(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
button1 = ttk.Button(self, text="Show Graph A",
command = lambda: controller.show_frame(GraphPageA))
button1.grid(row=1, column=0,pady=20,padx=10, sticky='w')
canvasB = FigureCanvasTkAgg(b, self)
canvasB.show()
canvasB.get_tk_widget().grid(row=1, column=1, pady=20,padx=10, sticky='nsew')
app = TransientAnalysis()
app.geometry("800x600")
aniA = animation.FuncAnimation(a, updateGraphs, interval=1000)
aniB = animation.FuncAnimation(b, updateGraphs, interval=1000)
app.mainloop()
更具体地说,正确显示绘图的页面是for循环中调用的最后一个on for F in ( GraphPageA, GraphPageB):
我还尝试使用不同的updategraph函数,每个图一个,但结果是相同的。
如何让两个TKinter页面绘制这两个不同的图形? 我正在使用Python2.7。
问题是第一次绘制图形时动画就被启动了。无论出于什么原因(这将是Tk或mpl的一些讨厌的内部细节),非初始可见轴的绘制事件永远不会被触发(或者在创建动画之前被触发),因此第二个动画甚至永远不会启动。通过向类中添加
canvas
属性,您可以在每次切换显示的图形时显式触发draw_idle
。请注意,我还:
在更一般的级别上,您可能应该将
GraphPage*
类重构为一个参数化类,该类负责:例如:
这显然引起了我今天的注意。。
相关问题 更多 >
编程相关推荐