I am using matplotlib with tkinter and I wanted the graphic screen/canvas/plot to be inside of the tkinter window so I made the matplotlib window into a widget inside of tkinter:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
window = tk.Tk()
fig, ax = plt.subplots()
frame = tk.Frame(window)
frame.pack()
label = tk.Label(window,text="test")
label.pack()
canvas = FigureCanvasTkAgg(fig, master=frame)
canvas.get_tk_widget().pack()
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()
canvas.get_tk_widget().destroy()
window.mainloop()
but now, when the window is closed, the python terminal keeps on running, making it impossible to close if there is no console tab opened. I have looked online about this issue and it is said I have to repeat plt.show() twice at the end to make matplotlib close but since I am not using plt.show() method to display the graphics, it is impossible to close. Please help me about this issue
>Solution :
As you said, plt.show() won’t work in this case because you’re embedding the Matplotlib plot into a Tkinter window. To handle closing the window properly, you can use the destroy() method of the Tkinter window to properly clean up when the window is closed. Here is the modified code:
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()