图片无法显示在tkinter Canvas

时间:2017-03-20 11:33:03

标签: python-2.7 tkinter

我正在尝试创建一个新的Canvas类,它将能够显示和调整图像大小。但是图像不显示。我搜索了类似的问题,并且所有答案都说要在课堂上保留PhotoImage的参考。(This answer for example)。我尝试过多种方式,但都没有效果。在这个例子中,我尝试在字典中保存引用。我也尝试了self.tkimage = ImageTk.PhotoImage(image=img),但没有成功。并尝试使用全局变量。我认为它与垃圾收集器有关,但不知道如何解决。 请协助。

import Tkinter as tk
from PIL import ImageTk, Image
import numpy as np
# a subclass of Canvas
class MyCanvas(tk.Canvas):
    def __init__(self,parent,**kwargs):
        tk.Canvas.__init__(self,parent,**kwargs)
        self.tkimg = {}
        self.images = []
        self.image_on_canvas = []

    def my_create_image(self, *args, **kw):
        img = kw['image']
        self.images.append(img)
        self.tkimg[img] = ImageTk.PhotoImage(image=img)
        kw['image'] = self.tkimg[img]
        item = self.create_image(*args, **kw)
        self.image_on_canvas.append(item)



def main():
    root = tk.Tk()
    myframe = tk.Frame(root)
    myframe.pack(fill=tk.BOTH, expand=tk.YES)
    mycanvas1 = MyCanvas(myframe, width=850, height=400, bg="red", highlightthickness=0)

    mycanvas2 = MyCanvas(myframe, width=850, height=400, bg="green", highlightthickness=0)
    mycanvas1.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.YES)
    mycanvas2.pack(side=tk.RIGHT, fill=tk.BOTH, expand=tk.YES)

    # add some widgets to the canvas

    mycanvas2.create_line(0, 100, 200, 0, fill="red", dash=(4, 4))
    mycanvas2.create_rectangle(50, 25, 150, 75, fill="blue")
    arr1 = np.random.random([256,256])*255
    img1 = Image.fromarray(arr1)
    mycanvas1.my_create_image(0, 0, image=img1, anchor=tk.NW)
    root.mainloop()


if __name__ == "__main__":
    main()

0 个答案:

没有答案