Python 3.x 为什么我需要类成员在画布上显示图像?

Python 3.x 为什么我需要类成员在画布上显示图像?,python-3.x,tkinter,raspberry-pi,python-3.5,tkinter-canvas,Python 3.x,Tkinter,Raspberry Pi,Python 3.5,Tkinter Canvas,将图像置于白色背景上 如果我尝试使用变量image\u tk而不是self.image\u tk它不会显示image 通常,当您单独使用image\u tk时,Python将在垃圾收集中捕获并删除它。为了防止这种情况发生,即实际显示图像,您必须将其绑定到垃圾收集中未捕获的更永久的对象。其中一种方法是在类内,通过引用self 因此,使图像能够显示的并不是实际的类,而是这样一个事实,即当“附加”到类中的self时,它不会被Python清除,因此就让它出现。我对Python非常陌生,所以请不要介意我的

将图像置于白色背景上

如果我尝试使用变量
image\u tk
而不是
self.image\u tk
它不会显示image


通常,当您单独使用
image\u tk
时,Python将在垃圾收集中捕获并删除它。为了防止这种情况发生,即实际显示图像,您必须将其绑定到垃圾收集中未捕获的更永久的对象。其中一种方法是在类内,通过引用
self


因此,使图像能够显示的并不是实际的类,而是这样一个事实,即当“附加”到类中的
self
时,它不会被Python清除,因此就让它出现。

我对Python非常陌生,所以请不要介意我的有意义的编码样式。所以,如果我没有错的话,任何必须在画布上显示的东西都应该连接到self?@codetolive只有图像以这种方式被垃圾收集,其他画布对象(椭圆、矩形、多边形…)不需要连接到self才能可见。
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))
       self.canvas = tk.Canvas(self, bg='white')

       self.canvas.config(height=self.screen_height, 
                 width=self.screen_height, highlightthickness=0)
       self.canvas.pack()
    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()