import io
#python -m pip install pillow (pillow是3版本之後的包PIL是2版本的)
from PIL import Image, ImageTk
import tkinter as tk
def resize(w, h, w_box, h_box, pil_image):
'''
resize a pil_image object so it will fit into
a box of size w_box times h_box, but retain aspect ratio
對一個pil_image對象進行縮放,讓它在一個矩形框內,還能保持比例
'''
f1 = 1.0*w_box/w # 1.0 forces float division in Python2
f2 = 1.0*h_box/h
factor = min([f1, f2])
#print(f1, f2, factor) # test
# use best down-sizing filter
width = int(w*factor)
height = int(h*factor)
return pil_image.resize((width, height), Image.ANTIALIAS)
root = tk.Tk()
# size of image display box you want
#期望圖像顯示的大小
w_box = 400
h_box = 200
# open as a PIL image object
#以一個PIL圖像對象打開
pil_image = Image.open(r'S.png')
# get the size of the image
#獲取圖像的原始大小
w, h = pil_image.size
# resize the image so it retains its aspect ration
# but fits into the specified display box
#縮放圖像讓它保持比例,同時限制在一個矩形框範圍內
pil_image_resized = resize(w, h, w_box, h_box, pil_image)
# convert PIL image object to Tkinter PhotoImage object
# 把PIL圖像對象轉變爲Tkinter的PhotoImage對象
tk_image = ImageTk.PhotoImage(pil_image_resized)
# put the image on a widget the size of the specified display box
# Label: 這個小工具,就是個顯示框,小窗口,把圖像大小顯示到指定的顯示框
label = tk.Label(root, image=tk_image, width=w_box, height=h_box)
#padx,pady是圖像與窗口邊緣的距離
label.pack(padx=5, pady=5)
root.mainloop()
py3.6 tk圖片縮放
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.