一、问题
python tkinter matplotlib 的使用中经常遇到这个报错,然后程序闪退:“alloc: invalid block: 1A6A6480: e8 28”
二、搜索结果 1 及其2个解决方案
https://github.com/matplotlib/matplotlib/issues/4013/
1、问题描述
I could not have multiple savefig() 's with different styles.
I wrote a sample code on stackoverflow.
http://stackoverflow.com/questions/28024050/multiple-savefig-s-with-different-styles/28024420?noredirect=1#comment44438695_28024420
I got some help somebody posted his results (as a picture). If I copy-paste his code, and run it I got an “alloc: invalid block” error.
2、评论回复(提出matplotlib.use指定特定backend来解决(我从 Agg 改为 TkAgg,亲测上百次都没出现,我的问题好像用这个方案解决了))
3、评论回复(提出函数末尾加上 plt.close() 来解决
三、搜索结果 2 及其2个解决方案:每次都能复现这个报错!同样是这个报错,并且明确有2种有效的解决方式。可借鉴和助于思考真实的原因【https://www.thinbug.com/q/35122511】
1、我收到错误alloc:invalid block:047129A8:c0 4当我使用create_text将文本添加到画布时。
这是一个示例程序。如果删除了create_text,则单击该矩形将关闭该程序,但在添加文本后,程序将关闭,但会显示错误消息,并且弹出窗口显示python已停止工作。
如果我用quit()替换destroy(),它可以正常工作。 (Python 3.5)
import tkinter as TK
import matplotlib.pyplot as plt
class MyButton:
def __init__(self):
self.master = TK.Tk()
self.canvas_width = 200
self.canvas_height = 200
self.canvas = TK.Canvas(self.master, width=self.canvas_width, height=self.canvas_height)
my_button = self.canvas.create_rectangle([10, 10, 110, 30], fill='lightgrey')
self.canvas.tag_bind(my_button, "<ButtonPress-1>", self.test) # lambda x: self.action(x,DOWN))
self.canvas.pack()
self.canvas_id = self.canvas.create_text(10, 50, anchor="nw")
self.canvas.itemconfig(self.canvas_id, text="this is the text")
TK.mainloop()
def test(self, e):
"""执行 2.1 会报alloc后崩溃;
改为 2.2 就不会;
执行 2.1 前先执行 1 也不会崩溃"""
print('Clicked')
# self.canvas.quit() # widget控件也是有这个方法的
plt.close()
# self.canvas.delete(self.canvas_id) # delete the text 【1】
self.master.destroy() # Clicked alloc: invalid block: 04B704C0: 90 4 【2.1】
# self.master.quit() # Clicked 【2.2】
if __name__ == '__main__':
b = MyButton()
2、我也多次遇到这个问题,但现在我想出了办法。您只需要在关闭窗口之前删除文本即可。
def test(self, e):
print('Clicked')
self.canvas.quit() # widget控件也是有这个方法的
self.canvas.delete(self.canvas_id) # delete the text
# self.master.quit() # Clicked
# self.master.destroy() # Clicked alloc: invalid block: 04B704C0: 90 4