[英]How to correctly close a tk.Toplevel that includes a matplotlib animation chart inside
I have created a Tkinter GUI that when a button is pushed, creates a tk.Toplevel.我创建了一个 Tkinter GUI,当按下按钮时,它会创建一个 tk.Toplevel。 This tk.Toplevel includes a matplotlib animated chart that is inserted as a tk widget.此 tk.Toplevel 包括一个 matplotlib 动画图表,该图表作为 tk 小部件插入。 My problem is that when I close the tk.Toplevel and I push the button to create another tk.Toplevel, a matplotlib figure is generated apart from the desired tk.Toplevel .我的问题是,当我关闭 tk.Toplevel 并按下按钮创建另一个 tk.Toplevel 时,除了所需的 tk.Toplevel 之外,还会生成一个 matplotlib 图形。 I have tried using 'WM_DELETE_WINDOW' tk.Toplevel closing protocol and do:我尝试使用 'WM_DELETE_WINDOW' tk.Toplevel 关闭协议并执行以下操作:
plt.close()
tk.Toplevel.destroy()
But doing this both the main GUI and the tk.Toplevel were closed.但是这样做,主 GUI 和 tk.Toplevel 都被关闭了。
The next lines of code represent a simplification of what I have reached with my program:接下来的代码行代表了我对我的程序所做的简化:
import tkinter as tk
import matplotlib
import matplotlib.figure as mf
import matplotlib.pyplot as plt
import matplotlib.animation as ani
from matplotlib.animation import FuncAnimation
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
container = tk.Frame(self)
container.pack()
frame = MAININTERFACE(parent=container, controller=self)
frame.grid(row=0, column=0, sticky="nsew")
def graph(self):
grafica1=GRAPHICATION(controller=self)
grafica1.Graph()
class MAININTERFACE(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.button=tk.Button(self, text='GRAPH', command=lambda: self.controller.graph())
self.button.pack(pady=20)
class GRAPHICATION(tk.Frame):
def __init__(self,controller):
tk.Frame.__init__(self)
self.controller=controller
self.x=[]
self.y=[]
def animation_frame(self, i):
if i==0.0:
self.time=0
self.energy=0
else:
self.time=self.time+1
self.energy=self.energy+1
self.x.append(self.time)
self.y.append(self.energy)
self.line.set_data(self.x,self.y)
self.ax.axis([0,10,0,10])
def Graph(self):
self.graphtoplevel=tk.Toplevel(self.controller)
self.graphtoplevel.title('Toplevel')
self.fig, self.ax = plt.subplots()
self.graph=FigureCanvasTkAgg(self.fig, self.graphtoplevel)
self.image=self.graph.get_tk_widget()
plt.ion()
self.line, = self.ax.plot(self.x,self.y)
self.image.grid(row=0, column=0, sticky='nsew')
self.animation=FuncAnimation(self.fig,func=self.animation_frame,frames=np.arange(0,11,1),interval=500, repeat=False)
if __name__ == "__main__":
app = SampleApp()
app.geometry('500x200')
app.title('MAIN GUI')
app.mainloop()
Hope that my question is understood.希望我的问题能被理解。 Thank you.谢谢你。
This issue can be solved by deleting plt.ion()
or doing plt.ioff()
when closing the tk.Toplevel.这个问题可以通过在关闭 tk.Toplevel 时删除plt.ion()
或执行plt.ioff()
来解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.