0

I am running a simple tkinter application that plots some data with an animated graph. When using matplotlib.figure.Figure and add_subplot, when I close the window with the upper-menu 'X' button (windows default) the program terminates well. Working code:

self.f = matplotlib.figure.Figure(figsize=(6, 4), dpi=100)
self.ax = self.f.add_subplot(111)

Now, when I try to use matplotlib.pyplot.figure together with matplotlib.pyplot.subplot2grid, then the 'X' does close the window but the program keeps running.

self.f = plt.figure(figsize=(6, 4), dpi=100)
self.ax = plt.subplot2grid((6,4), (0,0), rowspan=6, colspan=4)

I've tried adding matplotlib.pyplot.close("all") at the end of the program but the app doesn't exit the mainloop at all:

app = myApp()
app.mainloop() # doesn't exit
plt.close("all") # doesn't get executed

Any possible reason and alternatives?

PS: Using self.protocol("WM_DELETE_WINDOW", self.destroy) doesn't work (where self is the tk.TK instance).

3
  • Using pyplot in a GUI application like tkinter can lead to problems due to the GUI mainloop and the pyplot state machine both trying to manage the same objects. I would recommend not using pyplot at all when embedding matplotlib in GUIs; this allows to circumvent such problems from the start. Commented Jun 21, 2018 at 10:50
  • @ImportanceOfBeingErnest things like that won't be gracefully handled even with the use of threads / processes? Also, are you aware if such issues occur with other Python GUI frameworks such as wxPython and PyQt/Pyside? Commented Jun 21, 2018 at 11:01
  • Such things can occur when combining pyplot with any other framework which starts an eventloop. You can treat pyplot isolated, i.e. if the GUI does not show any plot itself, but as said, the easiest is really to get rid of pyplot in your code completely. There should never be any reason to use pyplot at all (it's just a convenience thing if you don't want to create your own GUI - which you do here anyways) Commented Jun 21, 2018 at 11:05

1 Answer 1

2

You can try handling the WM_DELETE_WINDOW event and close all plots like this:

import matplotlib.pyplot as plt

def on_closing():
   plt.close("all")
   app.destroy()

app = myApp()
.
.
.
app.protocol("WM_DELETE_WINDOW", on_closing)
app.mainloop()
Sign up to request clarification or add additional context in comments.

1 Comment

The "all" in plt.close() is what, after trying many similar yet different approaches, finally did the trick for me. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.