在Tkinter中加载大图像会导致内存

2024-09-30 01:37:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我的背景是我是一名自学编程的微生物学家。如果有更简单的方法来做到这一点或者清理我的代码,我总是乐于接受建设性的批评和改进的方法。我尝试使用python的tkinter创建一个GUI,使用以下代码:

import sys
import cv2

from tkinter import *
from PIL import ImageTk, Image
import cv2

class TypeOneDetectionEditor(object):
    def __init__(self):

        image_file = "6wk_Control_B_01.png"  # Update the file as needed

        self.image_cv = cv2.imread(image_file)
        self.resize_factor = 0.1
        self.height, self.width, self.channel = self.image_cv.shape

        self.window = Tk()
        self.frame = Frame(self.window, bd=5, relief = SUNKEN)

        # Hard-code choice of resolution for canvas and scroll region as
        # maximum shape of images*resize_factor
        self.canvas = Canvas(self.frame, bg="#000000", width=1366, height=768,
                             scrollregion=(0, 0, self.width*self.resize_factor,
                                           self.height*self.resize_factor))

        # Scrollbars
        hbar=Scrollbar(self.frame,orient=HORIZONTAL)
        hbar.pack(side=BOTTOM,fill=X)
        hbar.config(command=self.canvas.xview)
        vbar=Scrollbar(self.frame,orient=VERTICAL)
        vbar.pack(side=RIGHT,fill=Y)
        vbar.config(command=self.canvas.yview)
        self.canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)

        # Img + Event listeners
        # Literally because tkinter can't handle references properly and needs this.
        self.canvas.image = ImageTk.PhotoImage(Image.fromarray(self.image_cv))
        # So we can change the image later
        self.canvas_image_config = self.canvas.create_image(0, 0,
                                                            image=self.canvas.image,
                                                            anchor="nw")
        # Sets the focus to our program besides putting it in the background
        self.canvas.focus_set()
        # Put future functions here
        self.canvas.pack(side=LEFT)
        self.window.mainloop()

TypeOneDetectionEditor()

我收到的错误说明:

^{pr2}$

我更新了我的tkinter和pillow库,但仍然没有解决问题。我尝试使用的图片是604MB(太大了,无法上传到这篇文章),我的电脑上有16GB的内存。我不知道发生了什么,所以在这一点上任何建议都会有帮助。在


Tags: theimageimportselfconfigtkintercv2frame

热门问题