为什么我需要 Class 会员才能在 Canvas 上显示图像?

Why do i need Class Member to Show image on Canvas?

import tkinter as tk

from PIL import Image, ImageTk

class ImageViewer(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        self.screen_width = self.winfo_screenwidth()
        self.screen_height = self.winfo_screenheight()

        self.geometry("%dx%d%+d%+d" % (self.screen_width, 
                        self.screen_height, 0, 0))

putting image on white background

       self.canvas = tk.Canvas(self, bg='white')

       self.canvas.config(height=self.screen_height, 
                 width=self.screen_height, highlightthickness=0)
       self.canvas.pack()

If i try to use variable image_tk instead of self.Image_tk it doesn't show image

    def show_image(self):
        image = Image.open("./image1.jpg")

        image_width, image_height = image.size

        window_width = int(self.canvas['width'])
        window_height = int(self.canvas['height'])
        window_centre_x = window_width / 2
        window_centre_y = window_height / 2

        if image_width > window_width or image_height > window_height:

            image.thumbnail((window_width, window_height), 
               Image.ANTIALIAS)
            self.image_tk = ImageTk.PhotoImage(image)
            self.canvas.create_image(window_centre_x, window_centre_y, 
                image=self.image_tk, anchor=tk.CENTER, tag='i')
        else:
            scale_x = float(window_width) / image_width
            scale_y = float(window_height) / image_height

            if scale_x > scale_y:
               scale = scale_y
            else:
               scale = scale_x

            scaled_width = int(image_width * scale)
            scaled_height = int(image_height * scale)

            image = image.resize((scaled_width, scaled_height), 
                           Image.ANTIALIAS)
            self.image_tk = ImageTk.PhotoImage(image)
            self.canvas.create_image(window_centre_x, window_centre_y, 
                 image=self.image_tk, anchor=tk.CENTER, tag='i')

img = ImageViewer()
img.show_image()
img.mainloop()

通常当您单独使用 image_tk 时,Python 会在垃圾回收中捕获并删除它。为了防止这种情况发生,即实际显示图像,您必须将其绑定到更永久的东西上,而这些东西不会被垃圾收集所捕获。一种方法是在 class 内,通过引用 self.

所以,并不是真正的class让图像显示出来,而是当'attached'到self在你的class中,它是未被 Python 清除,因此让它出现。