Tkinter error: Couldn't recognize data in image file

后端 未结 5 1382
独厮守ぢ
独厮守ぢ 2021-01-04 01:12

I\'m trying to put a jpg image to a tkinter canvas. tkinter gives me this error:

couldn\'t recognize data in image file

I use th

5条回答
  •  时光取名叫无心
    2021-01-04 01:49

    Your code seems right, this is running for me on Windows 7 (Python 3.6):

    from tkinter import *
    root = Tk()
    
    canv = Canvas(root, width=80, height=80, bg='white')
    canv.grid(row=2, column=3)
    
    img = PhotoImage(file="bll.jpg")
    canv.create_image(20,20, anchor=NW, image=img)
    
    mainloop()
    

    resulting in this tkinter GUI:

    with this image as bll.jpg:

    (imgur converted it to bll.png but this is working for me as well.)


    More options:

    • This answer mentions, tkinter is working only with gif images. Try using a .gif image.
    • If this is not working, use PIL as stated in this answer.

    Update: Solution with PIL:

    from tkinter import *
    from PIL import ImageTk, Image
    root = Tk()
    
    canv = Canvas(root, width=80, height=80, bg='white')
    canv.grid(row=2, column=3)
    
    img = ImageTk.PhotoImage(Image.open("bll.jpg"))  # PIL solution
    canv.create_image(20, 20, anchor=NW, image=img)
    
    mainloop()
    

提交回复
热议问题