最近來使用tkinter加載圖片時遇到了困難,按照資料寫了
photo = PhotoImage(file='ques.png') imglabel = Label(root, image=photo) imglabel.grid(row=0, column=0, columnspan=3)
卻意外報錯
經過多種嘗試無果,最后發現tkinter是只支持gif的格式,如果要加載png或者jpg的話就要使用PIL模塊:
from Tkinter import * from PIL import Image, ImageTk root = Tk() root.title('測試組python畢業題') img = Image.open('ques.png') # 打開圖片 photo = ImageTk.PhotoImage(img) # 用PIL模塊的PhotoImage打開 imglabel = Label(root, image=photo) imglabel.grid(row=0, column=0, columnspan=3) Label(root, text="Answer:").grid(row=1, column=0, sticky=S + N) answerEntry = Entry(root) btn = Button(root, text="Submit", command=submit) answerEntry.grid(row=1, column=1) btn.grid(row=1, column=2) mainloop()
最后正確顯示了png圖片