Cropping an image in tkinter

北城以北 提交于 2020-05-23 21:33:28

问题


I'm using tkinter and I have a "sprite sheet" and I want to cut it into multiple images. I tried PIL:

img = Image.open("test.png").convert("RGBA")
img2 = img.crop([300,300,350,350])
image = ImageTk.PhotoImage(img2)
win = tk.Tk()
label = tk.Label(win, image = image)
label.pack()

but on my window, there is only an empty white rectangle and I don't understand why. Moreover I tried img2.show() just to make shure that img2 wasn't empty and it wasn't.


回答1:


Here is your code, with a few changes. Note the call to Tk() at the top, and mainloop() at the bottom. The other modification is that it obtains the width and height of the image and then crops 25% from each of the four sides to leave the middle 50% of the image.

#!/usr/bin/python

from tkinter import *  
from PIL import ImageTk,Image  

root = Tk()

img = Image.open("test.png").convert("RGBA")

w, h = img.size

left = w/4
right = 3*w/4
upper = h/4
lower = 3*h/4

img2 = img.crop([ left, upper, right, lower])
image = ImageTk.PhotoImage(img2)

label = Label(root, image = image)
label.pack()

root.mainloop()


来源:https://stackoverflow.com/questions/52375035/cropping-an-image-in-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!