简体   繁体   中英

Matplotlib in tkinter can not exit

I modified some matplotlib examples for test,this is code

#!/usr/bin/env python
import matplotlib
matplotlib.use('TkAgg')

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

import sys
if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk

root = Tk.Tk()
root.wm_title("test in TK")

f = plt.figure(figsize=(3,3),dpi=98)

labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')

plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=90)

plt.axis('equal')

canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

button = Tk.Button(master=root, text='Quit', command=sys.exit)
button.pack(side=Tk.BOTTOM)

Tk.mainloop()

I put a pie in tk,it can work,if I press 'Quit' button program will exit normally,if I press tk's 'X' the window will close,but this program in CMD window always waiting,not exit,I need use Ctrl+Break to close it,why?

The pyplot library provides a MATLAB-like plotting framework. It will make life easier for you by creating threads in the background, so that you can communicate with the pyplot user interface at the same time as using a CLI or some other interface. I guess what is happening is that this helper thread does not terminate when you press quit, and therefore the program does not exit. You should probably avoid using pyplot when making your own GUI.

One workaround could be this:

def exit():
    plt.close('all')
    sys.exit()

which would close all pyplot plots. But the best thing would probably be not to use pyplot in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM