正如你所说,
plt.show()
在这种情况下不起作用,因为您正在将Matplotlib绘图嵌入到Tkinter窗口中。为了正确地处理关闭窗口的问题,可以使用Tkinter窗口的destroy()方法在关闭窗口时正确地进行清理。这是修改后的代码:
import tkinter as tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTk, NavigationToolbar2Tk
def draw():
ax.hist([1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5], 5)
canvas.draw()
def on_closing():
window.destroy()
plt.close() # Close the Matplotlib plot
window = tk.Tk()
window.protocol("WM_DELETE_WINDOW", on_closing) # Handle window closing event
fig = Figure()
ax = fig.add_subplot(111)
canvas = FigureCanvasTk(fig, master=window)
canvas_widget = canvas.get_tk_widget()
canvas_widget.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
toolbar = NavigationToolbar2Tk(canvas, window)
toolbar.update()
canvas_widget.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
draw_button = tk.Button(window, text="Draw", command=draw)
draw_button.pack()
window.mainloop()