Cheang Wai Bin
Cheang Wai Bin

Reputation: 143

Program does not end when plotting in tkinter

I'm actually plotting a stacked bar and line chart together but to simplify the code I'm showing a simple bar chart only.

from tkinter import *
import matplotlib.pyplot as plt

window = Tk()

fig, ax = plt.subplots()
name = ['a', 'b', 'c']
score = [1, 2, 3]
ax.bar(name, score)
plt.savefig('Figure1.png')

window.mainloop()

The code itself is doing fine, the issue is when I exit tkinter GUI, the program does not close completely, as seen in powershell

PS C:\Users\Desktop> python temp.py
|

Without the plotting it will look like this after exiting tkinter GUI

PS C:\Users\Desktop> python temp.py
PS C:\Users\Desktop> |

I believe there is some extra closing code I need after plotting the figure in tkinter?

Upvotes: 1

Views: 130

Answers (1)

acw1668
acw1668

Reputation: 46688

You need to close the figure as well. Bind a function to WM_DELETE_WINDOW protocol and close the figure inside the function:

...

def on_quit():
    plt.close('all')
    window.destroy()

window.protocol('WM_DELETE_WINDOW', on_quit)
window.mainloop()

Upvotes: 2

Related Questions