Python使用tkinter显示图片(png、jpg)


使用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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM