python - tkinter 销毁错误将文本添加到 Canvas

标签 python canvas tkinter

当我使用 create_text 向 Canvas 添加文本时出现错误 alloc: invalid block: 047129A8: c0 4

这是一个示例程序。如果删除 create_text 单击矩形关闭程序,但在添加文本后程序关闭但出现错误消息并弹出一个窗口说 python 已停止工作。

如果我用 quit() 替换 destroy(),它工作正常。 ( python 3.5)

import tkinter as TK
class Button():
    def __init__(self):
        self.master = TK.Tk()
        canvas_width = 200
        canvas_height =200
        canvas = TK.Canvas(self.master, width=canvas_width,  height=canvas_height)
        button = canvas.create_rectangle([10,10,110,30],fill='lightgrey')
        canvas.tag_bind(button, "<ButtonPress-1>", self.test) # lambda x: self.action(x,DOWN))  
        canvas.pack()
        canvas_id = canvas.create_text(10, 50, anchor="nw")
        canvas.itemconfig(canvas_id, text="this is the text")
        TK.mainloop()
    def test(self, e):
        print ('Clicked')
        #self.master.quit()
        self.master.destroy()
if __name__ == '__main__':
    b = Button()

最佳答案

我也遇到过很多次这个问题,现在想出了办法。您只需在关闭窗口前删除文本即可。

import tkinter as TK
class Button():
    def __init__(self):
        self.master = TK.Tk()
        canvas_width = 200
        canvas_height = 200
        self.canvas = TK.Canvas(self.master, width=canvas_width,  height=canvas_height)
        button = self.canvas.create_rectangle([10,10,110,30],fill='lightgrey')
        self.canvas.tag_bind(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):
        print('Clicked')
        self.canvas.delete(self.canvas_id) #delete the text
        self.master.destroy()              #then close

if __name__ == '__main__':
    b = Button()

顺便说一下,我将 canvas 更改为 self.canvas 以便我可以在“测试”函数中访问它。

希望这对你有帮助:D

关于python - tkinter 销毁错误将文本添加到 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35122511/

相关文章:

具有可变深度的 Python 嵌套列表推导式

css - 如何在 HTML Canvas 中的移动分辨率上添加另一个图标

javascript - 如何在 HTML Canvas 上旋转矩形?

python - 在 Matplotlib 图形窗口中更改图标

python - 在哪里可以找到有关 python 3.2 的 tkinter 的文档或示例代码?

python - celery 任务消失 - Django/Celery

python - c api 中的 Numpy 记录

javascript - 在 Leaflet v0.8-dev 之上添加蒙版叠加层

drag-and-drop - tkinter 列表框拖放

python - 使用 Matplotlib 调整图形