如何正确关闭嵌入了 matplotlib 的 tkinter Toplevel?

How to properly close tkinter Toplevel with matplotlib embeded?

我正在制作一个 GUI 应用程序,我想使用 matplotlib 来显示一些绘图。 我的代码结构如下:

import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import matplotlib.pyplot as plt


class PopUP_Graph(tk.Toplevel):
    def __init__(self, *args, **kargs):
        super().__init__(*args, **kargs)
        self.fig, self.ax = plt.subplots()
        self.drawing_area = FigureCanvasTkAgg(self.fig, master=self)
        self.drawing_area.draw()
        self.toolbar = NavigationToolbar2Tk(self.drawing_area, self)
        self.toolbar.update()
        self.drawing_area.get_tk_widget().pack(side="top", fill="both", expand=1)


class App:
    def __init__(self, root):
        self.master = root
        self.button = tk.Button(root, text="Open graph", command=self.open_graph)
        self.button.grid(column=0, row=0)

    def open_graph(self):
        popupgraph1 = PopUP_Graph(self.master)
        popupgraph1.mainloop()


w, h = 900, 600
root = tk.Tk()
root.geometry(f'{w}x{h}+0+0')
app = App(root)
root.mainloop()

我遇到的问题是,当顶层 window 显示然后关闭时,即使关闭根 window,程序也不会正确关闭。

有办法解决这个问题吗??

正如 Henry Yik 指出的那样,应该使用 matplotlib.figure.Figure 而不是 pyplot。现在可以使用了:

import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure


class PopUP_Graph(tk.Toplevel):
    def __init__(self, *args, **kargs):
        super().__init__(*args, **kargs)
        # self.fig, self.ax = plt.subplots()
        self.fig = Figure()
        self.ax = self.fig.add_subplot()
        self.drawing_area = FigureCanvasTkAgg(self.fig, master=self)
        self.drawing_area.draw()
        self.toolbar = NavigationToolbar2Tk(self.drawing_area, self)
        self.toolbar.update()
        self.drawing_area.get_tk_widget().pack(side="top", fill="both", expand=1)


class App:
    def __init__(self, root):
        self.master = root
        self.button = tk.Button(root, text="Open graph", command=self.open_graph)
        self.button.grid(column=0, row=0)

    def open_graph(self):
        popupgraph1 = PopUP_Graph(self.master)
        popupgraph1.mainloop()


w, h = 900, 600
root = tk.Tk()
root.geometry(f'{w}x{h}+0+0')
app = App(root)
root.mainloop()