0

I'm trying to make a UI as an input, before closing this and then doing some plotting using pyplot. However, when I try to run a script using tkinter and importing matplotlib.pyplot, the program terminates at root = Tk() in the script, and will not run any commands after this line (including the mainloop).

Is there any way to use both tkinter and matplotlib.pyplot in the same script?

The UI I am running is:

from tkinter import *

class InputSelect(Frame):
    def __init__(self, master):
        self.master = master
        Frame.__init__(self, master, width=200, height=200)
        self.fillCanvas()

    def fillCanvas(self):
        self.canvas = Canvas(self, width=200, height=200)
        self.canvas.pack()

        self.aButton = Button(self, text="a", height=1, width=15, command=self.buttontest)
        self.aButtonWindow = self.canvas.create_window(100, 80, window=self.aButton)

        self.pack()

    def buttontest(self):
        print("buttontest")

def generateInputSelect():
    print("test")
    root = Tk()
    print("test2")
    app = InputSelect(root)
    app.mainloop()

if __name__ == "__main__":
    generateInputSelect()

This runs fine on its own, but if I use it in a separate script:

import ui
import matplotlib.pyplot


ui.generateInputSelect()

The console prints "test" and then closes, it doesn't reach "test2". This separate script runs as expected if I remove import matplotlib.pyplot.

Jon
  • 109
  • 2
  • 3
  • 11

1 Answers1

0

After some discussion and further research, running the program through terminal led me to the error terminating with uncaught exception of type NSException.

I was able to fix this error by setting the TkAgg backend manually using

import matplotlib
matplotlib.use("TkAgg")
from matplotlib import pyplot as plt

as suggested by DonCristobal at Matplotlib Crashing tkinter Application

This issue appears to be related to MacOS, which is why the error wasn't able to be reproduced by some users.

Jon
  • 109
  • 2
  • 3
  • 11