天天看點

使用tkinter加載png,jpg

最近來使用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圖檔