Python session kept open after closing tkinter window with a matplotlib graph

Question:

I want to put a matplotlib figure in a tkinter user interface. This is my code, based on the matplotlib documentation:

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

root = tk.Tk()

fig = plt.figure(figsize=(4,4))
ax = fig.add_subplot()
line, = ax.plot([1,2,3],[1,4,9])

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()

toolbar = NavigationToolbar2Tk(canvas, root, pack_toolbar=False)
toolbar.update()

canvas.get_tk_widget().pack()
toolbar.pack()

tk.Button(root, text="Exit", command=lambda:sys.exit()).pack()

root.mainloop()

I runs correctly. The problem comes when I close the window. If I press the "X" button of the window, the terminal never finishes, but if I press the "Exit" button I added, it finishes. If instead I use root.destroy(), it neither works. How can I solve this issue?

Thanks!

Edit:

I uploaded a video in YouTube, so you can see my problem: https://youtu.be/qUkm-lnXRR8

I’m using Windows 11 PowerShell, version:

Name                           Value
----                           -----
PSVersion                      5.1.22621.963
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.22621.963
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Python version 3.11.1

Asked By: Abel Gutiérrez

||

Answers:

Following this GitHub issue, this solves the issue

import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import sys
from matplotlib.figure import Figure #### This is the difference

root = tk.Tk()

fig = Figure() # plt.figure()
ax = fig.add_subplot()

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()

toolbar = NavigationToolbar2Tk(canvas, root, pack_toolbar=False)
toolbar.update()

canvas.get_tk_widget().pack()
toolbar.pack()

tk.Button(root, text="Exit", command=lambda:sys.exit()).pack()

root.mainloop()

print("Hello")
Answered By: Abel Gutiérrez
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.