首页 > 解决方案 > 在 tkinter 中有效(实时)显示 PIL 图像?

问题描述

目前我正在编写一个程序,该程序需要允许用户绘制简单的线条,还可以绘制矩形来选择一个区域。我以前使用过 tkinter 的画布,但它在一些操作和内存泄漏方面有性能,所以我试图用枕头来代替。

这是我绘制矩形的代码:


  def drawRect(self, start, end):

        x1 = end[0]
        y1 = end[1]

        x0 = start[0]
        y0 = start[1]

        t0 = time()
        t = time()
        
        #size of image is roughly between 1000x1000 to 1080p
        rectLayer = Image.new("RGBA", self.backgroundImage.size)
        rectDraw = ImageDraw.Draw(rectLayer)
        rectDraw.rectangle([start, end], fill="#00000080")
        rectDraw.line((x0, y0, x1, y0, x1, y1, x0, y1, x0, y0), fill="#ffffff", width=1)
        print("drawing: ", time() - t)
        t = time()

        displayImage = Image.alpha_composite(self.backgroundImage, self.linesLayer)
        displayImage.alpha_composite(rectLayer, (0, 0), (0, 0))
        print("image blend: ", time() - t)
        t = time()

        self.photoImage = ImageTk.PhotoImage(displayImage)
        print("photoImage convert: ", time() - t)
        t = time()

        self.imageContainer.configure(image=self.photoImage)  # imageContainer is a Label
        print("label config: ", time() - t)
        print("total: ", time() - t0)

'''
Output for drawing a single rect:

    drawing:  0.001994609832763672
    image blend:  0.009583711624145508
    photoImage convert:  0.0139617919921875
    label config:  0.02194380760192871
    total:  0.049475669860839844
'''

我面临的问题是,虽然 PIL 速度很快,但显示该图像却不是。从我的时间分析来看,绘制矩形花费的时间很少,但是将图像转换为照片图像,然后将其设置为标签图像需要很长时间。我希望这个功能每秒至少可以运行 60 次左右,这样程序使用起来感觉更流畅。有没有办法可以更快地显示图像?

标签: pythontkinterpython-imaging-library

解决方案


推荐阅读