Tkinter 中的图像 canvas

Image in Tkinter canvas

我正在尝试使用 python 学习基本动画, 当我尝试将图像插入 tkinter canvas 时,没有看到错误,但图像也没有。

from tkinter import *
import time
from PIL import *


def initiate():
    canvas1 = Canvas(root, width=800, height=600)
    canvas1.pack(expand=YES, fill=BOTH)
    im = PhotoImage(file='flag.gif', height=100, width=100)
    canvas1.create_polygon(10, 10, 0, 20, 20, 20, fill='white')
    print("hi")
    canvas1.create_image(100, 100, image=im)
    print('bye')
    root.update()


root = Tk()
initiate()
root.mainloop()

已成功创建多边形,但未显示图像。 请告诉我我在这里做错了什么。 我需要图像在 canvas 中,而不是在标签中。

应该可行:

from tkinter import *

def initiate():
    canvas1 = Canvas(root, width=800, height=600)
    canvas1.pack(expand=YES, fill=BOTH)
    im = PhotoImage(file='flag.gif', height=100, width=200)
    canvas1.create_polygon(10, 10, 0, 20, 20, 20, fill='white')
    label = Label(image=im)
    label.image = im
    print("hi")
    canvas1.create_image(100, 100, image=im)
    print('bye')
    root.update()

root = Tk()
initiate()
root.mainloop()

输出:

详见Why do my Tkinter images not appear?