1

I am trying to learn basic animation using python, when i tried to insert an image into the tkinter canvas, no error is visible but neither is the image.

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()

the polygon is successfully crated but image is not being shown. pls tell me what i am doing wrong here. i need image to be in the canvas,not in label.

1 Answers1

0

That should work:

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()

Output:

enter image description here

See Why do my Tkinter images not appear? for detailed explanation.

Alderven
  • 7,569
  • 5
  • 26
  • 38