Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter/Matplotlib backend conflict causes infinite mainloop

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?

like image 847
TheoretiCAL Avatar asked Jul 08 '13 20:07

TheoretiCAL


1 Answers

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.

like image 146
unutbu Avatar answered Oct 04 '22 19:10

unutbu