在用Python创建画布canvas,并在画布上导入图像时报错:“_tkinter.TclError: couldn't recognize data in image file "F:\Python\test\a.gif"”

用tkinter只能装入GIF图片,也就是扩展名是.gif的图片文件,想要显示其他类型的图片,如png或jpg,需要用到其它模块 

def canvas_test():
    import tkinter
    
    window = tkinter.Tk()
    window.geometry('600x400')
    window.title('This is Canvas')
    
    #创建550 * 300的画布
    canvas = tkinter.Canvas(window, bg='green', width=550, height=300)    
    #在画布上创建图像,放置导入图片
    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()

 在网上寻找解决办法,了解到更改图片后缀并不能修改图片格式。(网上参考:https://stackoverflow.com/questions/28740462/tkinter-couldnt-recognize-data-in-image-file)

所以,重新百度搜索一张GIF图片,下载后命名为c.gif(或者d.jpg),只要保存图片格式为GIF Image,再运行以下代码:

def canvas_test():
    import tkinter
    
    window = tkinter.Tk()
    window.geometry('600x400')
    window.title('This is Canvas')
    
    #创建550 * 300的画布
    canvas = tkinter.Canvas(window, bg='green', width=550, height=300)
    
    #在画布上创建图像,放置导入图片
    #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()

代码运行正常,图片显示正常,只是显示静态图片。

PhotoImage的图片检查只看图片本身的类型,与图片名称后缀无关。

posted on 2019-08-12 15:36  懒惰的Grace  阅读(14627)  评论(0编辑  收藏  举报