简体   繁体   中英

Python tkinter freezes when trying to use matplotlib to save an image

I have a basic tkinter GUI running with a few inputs and a submit button. When the submit button is hit, some data is created, and a plot should be generated/saved:

import matplotlib.pyplot as plt
plt.plot(x1,y1,'go',x2,y2,'bo')
plt.savefig(filename)
plt.clf()

The plot does not need to be displayed with matplotlib; it just needs to be saved. However, my tkinter GUI freezes up when this line is reached:

plt.plot(x1,y1,'go',x2,y2,'bo')

Another tkinter window pops up at that point (a blank, grey window with title 'tk'). It seems matplotlib is interfering with tkinter somehow. But I don't need matplotlib to open up a window (just require a plot to be saved), so I am kind of confused as to why this is happening.

(Btw, I have two threads running (one that updates a progress bar, and one that does some calculations), though I am pretty sure this shouldn't be affecting anything).

You have multiple main event loops running which are interfering with each other. Either properly embed matplotlib in your gui ( examples ), or use a non-interactive backend:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot(x1,y1,'go',x2,y2,'bo')
plt.savefig(filename)
plt.clf()

When you import pyplot you are importing a whole slew of convince functions (see Which is the recommended way to plot: matplotlib or pylab? ), which includes a gui system for interactive tok

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