这个问题的起因是想做一个文件选择器,选择图片之后用PIL缩放,然后渲染到tkinter的canvas里。然后我写了这么一段代码(为了简化这个问题,文件选择器改用写死的路径代替了):
import tkinter as tk
from PIL import Image, ImageTk
# ...
canvas_avatar = tk.Canvas(root, width=1800, height=1000) # root是整个窗口
ele_avatar = canvas_avatar.create_image(0, 0, anchor='nw')
pil_avatar = Image.open('avatar.png').resize((1800, 1000), Image.ANTIALIAS)
img_avatar = ImageTk.PhotoImage(pil_avatar)
canvas_avatar.itemconfig(ele_avatar, image=img_avatar)
canvas_avatar.pack()
看上去好像一切正常,并且运行也没有报错,但是页面上什么都没有;图片不见了。
后来查了一下,据说是Python的GC机制,会把图片在内存里给销毁了,所以需要绑定到不会被销毁的元素上,比如绑定到canvas本身上。所以,应该把代码改成这样:
import tkinter as tk
from PIL import Image, ImageTk
# ...
canvas_avatar = tk.Canvas(root, width=1800, height=1000) # root是整个窗口
ele_avatar = canvas_avatar.create_image(0, 0, anchor='nw')
pil_avatar = Image.open('avatar.png').resize((1800, 1000), Image.ANTIALIAS)
canvas_avatar.img_avatar = ImageTk.PhotoImage(pil_avatar)
canvas_avatar.itemconfig(ele_avatar, image=canvas_avatar.img_avatar)
canvas_avatar.pack()
这样就能正常显示了。