Tkinter/Matplotlib后端冲突导致无限主循环

The*_*CAL 7 python tkinter matplotlib

考虑运行以下代码(注意它是一个非常简化的版本来演示问题):

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()
Run Code Online (Sandbox Code Playgroud)

关闭第一个窗口将正常工作,但关闭第二个窗口会导致代码挂起,因为root.mainloop()会导致无限循环.此问题是由调用引起的fig = plot.figure(figsize=(16.8, 8.0)).在做出matplotlib.pyplot调用之后,有没有人知道如何让root成功关闭?

unu*_*tbu 7

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()
Run Code Online (Sandbox Code Playgroud)

Tkinter窗口中嵌入matplotlib图时,请使用matplotlib.figure.Figure而不是plt.Figure.

  • `plt.figure`使用一个数字管理器来处理主循环/ gui ect.`matplotlib.figure.Figure`只是一个`Figure`对象,你的问题是争论gui. (6认同)