python报错: _tkinter.TclError: couldn't recognize data in image file

在用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的图片检查只看图片本身的类型,与图片名称后缀无关。

转载于:https://www.cnblogs.com/Grace-gao/p/11340494.html

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值