解决tkinter.PhotoImage()仅支持gif等几种不常用的图片格式问题

如果想用 ".jpg"文件格式,直接用下面的代码,会报“couldn't recognize data in image file "C:\Users\happy\Desktop\test.jpg"错误。

photo = tk.PhotoImage(file="C:\\Users\\happy\\Desktop\\test.jpg") 
Lab= tk.Label(root,text='欢迎来到皮卡丘之家',compound='center',font = ('微软雅黑',30),image= photo)
Lab.pack()

因为tkinter.PhotoImage()仅支持 GIF and PGM/PPM 文件格式。

解决:

利用PIL包来实现,(支持30多种图片格式)代码如下:

import tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()
root.geometry('650x450+150+100')
root.title('Test')
root.resizable(False, False)

global photo
#设置条形框,插入图片
image = Image.open("C:\\Users\\happy\\Desktop\\test.jpg")
photo = ImageTk.PhotoImage(image) 
Lab= tk.Label(root,text='欢迎来到皮卡丘之家',compound='center',font = ('微软雅黑',30),image= photo)
Lab.pack()#设置主界面
 
root.mainloop()  

效果:

                            

参考官网:http://effbot.org/tkinterbook/photoimage.htm

发布了56 篇原创文章 · 获赞 29 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/foneone/article/details/103063945