Search code examples
pythonmatplotlibanimationtkintermatplotlib-widget

The python program is not ending when tkinter window is closed


I am working on a project to make Oscilloscope like GUI. Although GUI is not ready yet but I got a problem that the program is not being closed when I am closing the TKinter window. It is still running in python shell. I thought this might be the way to close tkinter related programs. But I found programs in which just by closing the tkinter window it kills the program. In my case the program is running in python shell even after closing the tkinter window. I am putting my code here please see where is the problem?

from tkinter import *
from matplotlib import pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np

root = Tk()
root.geometry("800x500+100+100")
root.title('root window')

frame = Frame(root, borderwidth=1,bg="#0DBDAB") ## This is the frame in which plot will be shown
frame.place(relx=1.0/3,rely=0.5, anchor="center", relwidth=0.60,relheight=0.8)
xar = [0]
yar = [0]
k=0.2  ### This is just a constant to make plot smoother
style.use('ggplot')
fig = plt.figure(figsize=(20,20), dpi=100)
ax1 = fig.add_subplot(1, 1, 1)
ax1.set_ylim(-1, 1)
line, = ax1.plot(xar, yar, 'r')

## It will not plot regularly instead add line for new data
def animate(i):
    ax1.set_xlim(left=max(0,i-20), right=i+1)
    yar.append(np.sin(i*k))
    xar.append(i)
    line.set_data(xar,yar)
    return line,

plotcanvas = FigureCanvasTkAgg(fig, frame)
plotcanvas.get_tk_widget().pack(side=BOTTOM,fill=BOTH,expand=True)
ani = animation.FuncAnimation(fig, animate, interval=1000, blit=False)

root.mainloop()

Solution

  • I've done a small change,anyway you must use this

    root.protocol("WM_DELETE_WINDOW", quit_me)

    see below, on my debian, launching the script from terminal and closing the tkinter window it works.

    from tkinter import *
    from matplotlib import pyplot as plt
    import matplotlib.animation as animation
    from matplotlib import style
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    import numpy as np
    
    def quit_me():
        print('quit')
        root.quit()
        root.destroy()
    
    root = Tk() 
    root.protocol("WM_DELETE_WINDOW", quit_me)
    root.geometry("800x500+100+100")
    root.title('root window')