在Tkinter中裁剪图像 [英] Cropping an image in tkinter

查看:121
本文介绍了在Tkinter中裁剪图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用tkinter,我有一个"sprite sheet",我想将其切成多个图像.我尝试了PIL:

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()

但是在我的窗口上,只有一个空白的白色矩形,我不明白为什么.此外,我尝试img2.show()只是为了确保img2不为空,也不为空.

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.

推荐答案

这是您的代码,进行了一些更改.请注意,顶部是对Tk()的调用,底部是对mainloop()的调用.另一个修改是获取图像的宽度和高度,然后从四个侧面的每一个裁剪25%,剩下图像的中间50%.

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()

这篇关于在Tkinter中裁剪图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆