Tag Archives: _tkinter.TclError: couldn’t recognize data in image file

python: _tkinter.TclError: couldn’t recognize data in image file

When creating canvas with Python and importing images on the canvas, an error occurs_ tkinter.TclError: couldn’t recognize data in image file “F:\Python\test\a.gif””

Tkinter can only load GIF images, that is. GIF extension of the image file, want to display other types of images, such as PNG or JPG, need to use other modules

def canvas_test():
    import tkinter
    
    window = tkinter.Tk()
    window.geometry('600x400')
    window.title('This is Canvas')
    
    #Create a canvas of 550 * 300
    canvas = tkinter.Canvas(window, bg='green', width=550, height=300)    
    # Create the image on the canvas and place the imported image
    image_file = tkinter.PhotoImage(file="F:\\Python\\test\\a.gif")
    image = canvas.create_image(300, 10, anchor='n', image=image_file)
    canvas.pack()
    
    window.mainloop()

Looking for a solution on the Internet, I learned that changing the image suffix can’t change the image format( Online reference: https://stackoverflow.com/questions/28740462/tkinter-couldnt-recognize-data-in-image-file )

So, search Baidu again for a GIF image, download it and name it c.gif (or d.jpg). As long as you save the image in GIF image format, run the following code:

def canvas_test():
    import tkinter
    
    window = tkinter.Tk()
    window.geometry('600x400')
    window.title('This is Canvas')
    
    #Create a canvas of 550 * 300
    canvas = tkinter.Canvas(window, bg='green', width=550, height=300)
    
    # Create the image on the canvas and place the imported image
    #image_file = tkinter.PhotoImage(file="F:\\gao\\Python\\test\\c.gif")
    image_file = tkinter.PhotoImage(file="F:\\gao\\Python\\test\\d.jpg")
    image = canvas.create_image(300, 10, anchor='n', image=image_file)    
    canvas.pack()
    
    window.mainloop()

The code runs normally, the picture is displayed normally, only the static picture is displayed

photo image only depends on the type of the image itself, and has nothing to do with the suffix of the image name