icetomtom
icetomtom

Reputation: 25

Cropping an image in tkinter

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.

Upvotes: 2

Views: 8864

Answers (1)

DrM
DrM

Reputation: 2525

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

Upvotes: 4

Related Questions