使用tk原生寫法,只能顯示gif圖片,網上有些人居然搞jpg,png的后綴.還貼圖可以實現,簡直坑!!!
原生寫法:(不推薦)
img = tkinter.PhotoImage(file = 'test.gif') label_img = tkinter.Label(root, image = img)
為了顯示jpg,png的圖片我搜索到了下面demo1的方法,
如果要加載png,jpg的圖片要使用PIL模塊 ( from PIL import Image, ImageTk )
將圖片重新編碼,達到可以執行的目的.
demo1:
import tkinter from PIL import Image, ImageTk img = Image.open('./code.jpg') w = tkinter.Tk() photo = ImageTk.PhotoImage(img) image_Label = tkinter.Label(w, image=photo) image_Label.pack() w.mainloop()
在實際過程中,我的圖片是從外部獲取來的,並不是一開始就存在的,
debug調試的時候正常,運行的時候不正常,搞了老半天......
結果是函數結束的時候,變量被回收了,
圖片顯示不出來.加上global 解決!!!
demo2:
import WX import tkinter from PIL import Image, ImageTk def btn(): global photo # 函數運行結束就被回收了,會顯示的是空白 img_byte = wx.get_code() wx.save_img(img_byte) # 保存圖片 img = Image.open('.\\code.jpg') photo = ImageTk.PhotoImage(img) image_Label = tkinter.Label(w, image=photo) image_Label.grid(row=0, column=1) if __name__ == '__main__': wx = WX.Scrapy() w = tkinter.Tk() btn = tkinter.Button(w, text='獲取驗證碼', command=btn) btn.grid(row=0, column=0) w.mainloop()
最后還是感謝,寫了下面帖子的人,指引了我正確的方向.
參考文獻: https://blog.csdn.net/qq_28888837/article/details/113716814
參考文獻: https://wenku.baidu.com/view/4973b277834d2b160b4e767f5acfa1c7aa0082d2.html