Tkinter 中Image类
Reference
- PhotoImage, http://effbot.org/tkinterbook/photoimage.htm
- BitmapImage, http://effbot.org/tkinterbook/bitmapimage.htm
Tkinter中的图像
tkinter与图像相关的有两个类,默认只支持四种格式的图像文件,并且不同格式图像采用不同的方法读取
- BitmapImage : To display bitmap (two-color) images in the
.xbm
formatbit_img = tk.BitmapImage(file=f[, background=b][, foreground=c])
- PhotoImage: To display full-color images in the
.gif
,.pgm
, or.ppm
formatphoto_img = tk.PhotoImage(file=f)
如果想要处理更多格式的图像,则需要使用 第三方库,Python Imaging Library (PIL) 。这个库的ImageTk 类就是可以在tkinter中支持更多的图像。 PIL只支持python2,python3后是用Pillow,其实是同一个库。
默认的两种图像类,可以通过结合Label组件显示出图像来。
# bitmap
logo = tk.BitmapImage('logo.xbm', foreground='red')
tk.Label(bitmap=logo).pack()
# color image
photo_img = tk.PhotoImage(file='18.gif')
tk.Label(root, image=photo_img).pack(side=tk.RIGHT)
# 在mac上为了使图像有效,必须让组件保存图片的引用,即
photo_img = tk.PhotoImage(file='18.gif')
my_label = Label(root, image=photo_img)
my_label.image = photo_img # keep a reference!
my_label.pack(side=tk.RIGHT)
注意,如果同时指定bitmap和image这两参数,image 优先。
# 在mac上,也可以通过pillow来显示图
from Tkinter import *
from PIL import ImageTk, Image
root = Tk()
# method 1
img1 = ImageTk.PhotoImage(file='bg.jpg')
Label(root, text="abc", image=img1).pack(side="top")
# method 2
img2 = Image.open("photo.png")
photo = ImageTk.PhotoImage(im)
Label(root, text="abc", image=img2).pack(side="top")
root.mainloop()