How to put a cropped image on a Tkinter Canvas in

2019-01-27 01:39发布

问题:

I found a lot of similar questions, but not quite the solution to this case : I want to

  1. Load an image file from disk
  2. Crop it (lazy or not)
  3. Place it on a TKinter canvas

And oh, it would even be better that step 1 would not need to be a gif-file, but even if it has to be I'll be happy. That's it..

I can load a file, I can crop it (In PIL) I can place it on a canvas (In TKinter), but I don't seem able to combine it all.. (So maybe a simple cast from PIL to TKinter is enough?) I'm a newbee in TKinter of course.

回答1:

There is ImageTk module in PIL.

from Tkinter import *
from PIL import Image, ImageTk

root = Tk()
canvas = Canvas(root, width=500, height=500)
canvas.pack()

im = Image.open("image.png")
cropped = im.crop((0, 0, 200, 200))
tk_im = ImageTk.PhotoImage(cropped)
canvas.create_image(250, 250, image=tk_im)

root.mainloop()