在用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的圖片檢查只看圖片本身的類型,與圖片名稱后綴無關。