Tkinter/Matplotlib后端冲突导致无限的主循环 [英] 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()
关闭第一个窗口会很好,但是关闭第二个窗口会导致代码挂起,因为 root.mainloop()
会导致无限循环.这个问题是由调用fig = plot.figure(figsize=(16.8, 8.0))
引起的.有人知道在进行该matplotlib.pyplot调用后如何成功获得root权限吗?
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?
推荐答案
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()
将matplotlib图形嵌入到 Tkinter
窗口中时,请使用 matplotlib.figure.Figure
,而不要使用 plt.Figure
.
When embedding a matplotlib figure inside a Tkinter
window, use matplotlib.figure.Figure
rather than plt.Figure
.
这篇关于Tkinter/Matplotlib后端冲突导致无限的主循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!