28

I am building an application that embeds a matplotlib figure into the GUI. The problem is that my app is crashing as soon as I add anything from matplotlib into my code (except for the imports, those work as usual). The problem occurs in my class Solver_App at tk.Tk.__init__(self, *args, **kwargs). When I run the code, I get a massive error and the app crashes. Here is some of my code:

import tkinter as tk
from tkinter import ttk

import matplotlib
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

# Setting up figures for integration in GUI:
fig_3D = plt.figure()
fig_2D = plt.figure()
a_3D = fig_3D.add_subplot(111, projection="3d")
a_2D = fig_2D.add_subplot(111)
a_3D.plot_wireframe([1, 2, 3, 4, 5], [1, 3, 7, 6, 4], [1, 2, 3, 4, 5], color="blue")

class Solver_App(tk.Tk, ttk.Frame):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)  # This is where the app crashes.

        # Equation frame holds everything related to the input and configuration of the equations.
        equation_frame = ttk.Frame(self)
        equation_frame.pack(side="bottom", fill="x", pady=50, padx=50)

        # More code goes here...

# There are more classes with a similar setup as the one above...

app = Solver_App()
app.mainloop()

And here is the massive error I get when running the code:

2015-08-14 15:18:29.142 Python[50796:18837594] -[NSApplication _setup:]: unrecognized selector sent to instance 0x10216a830
2015-08-14 15:18:29.143 Python[50796:18837594] An uncaught exception was raised
2015-08-14 15:18:29.143 Python[50796:18837594] -[NSApplication _setup:]: unrecognized selector sent to instance 0x10216a830
2015-08-14 15:18:29.144 Python[50796:18837594] (
    0   CoreFoundation                      0x00007fff9901b03c __exceptionPreprocess + 172
    1   libobjc.A.dylib                     0x00007fff9436476e objc_exception_throw + 43
    2   CoreFoundation                      0x00007fff9901e0ad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
    3   CoreFoundation                      0x00007fff98f63e24 ___forwarding___ + 1028
    4   CoreFoundation                      0x00007fff98f63998 _CF_forwarding_prep_0 + 120
    5   Tk                                  0x00000001024ad527 TkpInit + 476
    6   Tk                                  0x0000000102427aca Tk_Init + 1788
    7   _tkinter.so                         0x00000001006e5f2d Tcl_AppInit + 77
    8   _tkinter.so                         0x00000001006e30d6 Tkinter_Create + 934
    9   Python                              0x00000001000e44ce PyEval_EvalFrameEx + 28894
    10  Python                              0x00000001000e5ced PyEval_EvalCodeEx + 2349
    11  Python                              0x000000010003e8ba function_call + 186
    12  Python                              0x000000010000d3c8 PyObject_Call + 104
    13  Python                              0x00000001000e0cb9 PyEval_EvalFrameEx + 14537
    14  Python                              0x00000001000e5ced PyEval_EvalCodeEx + 2349
    15  Python                              0x000000010003e8ba function_call + 186
    16  Python                              0x000000010000d3c8 PyObject_Call + 104
    17  Python                              0x000000010002802c method_call + 140
    18  Python                              0x000000010000d3c8 PyObject_Call + 104
    19  Python                              0x000000010007b831 slot_tp_init + 81
    20  Python                              0x0000000100072d14 type_call + 212
    21  Python                              0x000000010000d3c8 PyObject_Call + 104
    22  Python                              0x00000001000e1b09 PyEval_EvalFrameEx + 18201
    23  Python                              0x00000001000e5ced PyEval_EvalCodeEx + 2349
    24  Python                              0x00000001000e5daf PyEval_EvalCode + 63
    25  Python                              0x000000010011048e PyRun_FileExFlags + 206
    26  Python                              0x000000010011083d PyRun_SimpleFileExFlags + 717
    27  Python                              0x000000010012810e Py_Main + 3262
    28  Python                              0x0000000100000e32 Python + 3634
    29  Python                              0x0000000100000c84 Python + 3204
    30  ???                                 0x0000000000000002 0x0 + 2
)
2015-08-14 15:18:29.144 Python[50796:18837594] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSApplication _setup:]: unrecognized selector sent to instance 0x10216a830'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff9901b03c __exceptionPreprocess + 172
    1   libobjc.A.dylib                     0x00007fff9436476e objc_exception_throw + 43
    2   CoreFoundation                      0x00007fff9901e0ad -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
    3   CoreFoundation                      0x00007fff98f63e24 ___forwarding___ + 1028
    4   CoreFoundation                      0x00007fff98f63998 _CF_forwarding_prep_0 + 120
    5   Tk                                  0x00000001024ad527 TkpInit + 476
    6   Tk                                  0x0000000102427aca Tk_Init + 1788
    7   _tkinter.so                         0x00000001006e5f2d Tcl_AppInit + 77
    8   _tkinter.so                         0x00000001006e30d6 Tkinter_Create + 934
    9   Python                              0x00000001000e44ce PyEval_EvalFrameEx + 28894
    10  Python                              0x00000001000e5ced PyEval_EvalCodeEx + 2349
    11  Python                              0x000000010003e8ba function_call + 186
    12  Python                              0x000000010000d3c8 PyObject_Call + 104
    13  Python                              0x00000001000e0cb9 PyEval_EvalFrameEx + 14537
    14  Python                              0x00000001000e5ced PyEval_EvalCodeEx + 2349
    15  Python                              0x000000010003e8ba function_call + 186
    16  Python                              0x000000010000d3c8 PyObject_Call + 104
    17  Python                              0x000000010002802c method_call + 140
    18  Python                              0x000000010000d3c8 PyObject_Call + 104
    19  Python                              0x000000010007b831 slot_tp_init + 81
    20  Python                              0x0000000100072d14 type_call + 212
    21  Python                              0x000000010000d3c8 PyObject_Call + 104
    22  Python                              0x00000001000e1b09 PyEval_EvalFrameEx + 18201
    23  Python                              0x00000001000e5ced PyEval_EvalCodeEx + 2349
    24  Python                              0x00000001000e5daf PyEval_EvalCode + 63
    25  Python                              0x000000010011048e PyRun_FileExFlags + 206
    26  Python                              0x000000010011083d PyRun_SimpleFileExFlags + 717
    27  Python                              0x000000010012810e Py_Main + 3262
    28  Python                              0x0000000100000e32 Python + 3634
    29  Python                              0x0000000100000c84 Python + 3204
    30  ???                                 0x0000000000000002 0x0 + 2
)
libc++abi.dylib: terminating with uncaught exception of type NSException

I have been referencing code from a tutorial [found here](http://pythonprogramming.net/how-to-embed-matplotlib-graph-tkinter-gui/"How to embed a Matplotlib graph to your Tkinter GUI"), but their example seems to work fine. What is causing this problem and how can it be fixed?

  • I am using Python 3.4, matplotlib 1.4.3, and running Mac OS Yosemite.
Camon
  • 1,003
  • 1
  • 10
  • 22
  • I feel like you've omitted the most important parts. See if you can distill this down to an [MCVE](http://stackoverflow.com/help/mcve), it will probably help you fix your problem. One tip while you do that: when embedding stuff in Tkinter, do not use `pyplot`; use the actual `Figure` you've imported. You've skipped the places where we could see if you're doing that or not. – Ajean Aug 15 '15 at 00:15
  • Try doing the following. `plt.rcParams['keymap.save'] = ''` This could be a result of the way mac has it's key bindings. The last time I had an NSException thrown by tkinter on a Mac it was due to the way tkinter and mac conflict with their key bindings. – Pythonista Aug 15 '15 at 19:08

7 Answers7

66

You need to set the TkAgg backend explicitly. I could reproduce your bug. With the following code, the problem is resolved.

import matplotlib
matplotlib.use("TkAgg")  # NOTE: import order matters
from matplotlib import pyplot as plt

Note that setting the TkAgg backend after importing pyplot does not work either; it crashes too. You need to set it before importing pyplot. (Tested with MPL 1.4.3, tkinter.TkVersion 8.6)

Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119
DonCristobal
  • 1,965
  • 21
  • 21
0

If you don't want to edit the code, you can use set the following environment variable that matplotlib is reading:

MPLBACKEND=TkAgg

This way, no matter when you import pyplot, it'll work

Adelin
  • 7,809
  • 5
  • 37
  • 65
0

After importing matplotlib.pyplot, set the following:

plt.rcParams['keymap.quit'] = ''

This will avoid a mess to be created if plotting is interrupted. It works for me.

Apostolos
  • 3,115
  • 25
  • 28
0

After importing matplotlib.pyplot, set the following:

plt.rcParams['keymap.quit'] = ''

This will avoid a mess to be created if plotting is interrupted. But only with a "soft" exit, i.e. with code (keyboard/mouse event, etc.). It doesn't solve the "mess" problem if the figure (window) is closed by clicking the "exit" button ("X"). (This has still to be solved ... I haven't!)

Example:

import numpy as np
from matplotlib import pyplot as plt

def keypress(e):
  global animation
  animation = False

plt.connect('key_press_event', keypress)
plt.rcParams['keymap.quit'] = '' # This will avoid mess if plotting is interrupted!

animation = True

delay = 0.5; animation = True
for i in range(1,10):
  if not animation: break
  y = np.random.normal(loc=0.5, scale=0.4, size=1000)
  plt.plot(y)
  plt.pause(delay)

During the animation, pressing any key will stop it smoothly.

Apostolos
  • 3,115
  • 25
  • 28
-1

@DonCristobal's answer helped me and therefore I tried to upvote or add a comment to it but stackoverflow prevents me from doing any of that citing certain points I must reach before I can comment or upvote. The solution suggested by @DonCristobal worked for my configuration given below:

Mac catalina, python 3.6 & matplotlib 3.0.3

Here is what i did -

Modified

import matplotlib.pyplot as plt

to

import matplotlib

matplotlib.use("TkAgg")

from matplotlib import pyplot as plt
M_S_N
  • 2,764
  • 1
  • 17
  • 38
-1

I am still getting crashes with this:

import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

f = plt.figure()
plt.plot(x, y)
f.show()
plt.pause(0.0001)

The window with a sinappears and then the kernel freezes. Windows 10 with Anaconda3

aquagremlin
  • 3,515
  • 2
  • 29
  • 51
-1

Once i updated to the latest Python environment (3.8.2) this error went away without the need to use matplotlib.use("TkAgg").

semsi
  • 1