Tkinter/Matplotlib backend conflict causes infinite mainloop

matplotlib, python, tkinter

Solution

import matplotlib
from tkinter import *

def main():

    fig = matplotlib.figure.Figure(figsize=(16.8, 8.0))

    root = Tk()
    w = Label(root, text="Close this and it will not hang!")
    w.pack()
    root.mainloop()

    print('Code *does* reach this point')

if __name__ == '__main__':
    main()

When embedding a matplotlib figure inside a `Tkinter` window, use `matplotlib.figure.Figure` rather than `plt.Figure`.

Problem

Consider running the following code (note it is an extremely simplified version to demonstrate the problem): ``` import matplotlib.pyplot as plot from tkinter import * #Tkinter if your on python 2 def main(): fig = plot.figure(figsize=(16.8, 8.0)) root = Tk() w = Label(root, text="Close this and it will hang!") w.pack() root.mainloop() print('Code never reaches this point') if __name__ == '__main__': main() ``` Closing the first window will work fine, but closing the second window causes the code to hang, as `root.mainloop()` causes an infinite loop. This problem is caused by calling `fig = plot.figure(figsize=(16.8, 8.0))`. Does anyone know how to get root to close succesfully after making that matplotlib.pyplot call?

Original source