Tkinter / Matplotlib conflict causes endless mainloop

Consider running the following code (note that this 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 will cause the code to hang because 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 complete successfully after calling matplotlib.pyplot?

+7
python matplotlib tkinter
source share
1 answer
 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 shape inside a Tkinter window, use matplotlib.figure.Figure , not plt.Figure .

+7
source share

All Articles