Home > database >  How do I resize a Tkinter Image without using PIL.Image?
How do I resize a Tkinter Image without using PIL.Image?

Time:04-26

My program is having conflicts between PIL Image/ImageTk and Tkinter. I want to resize a gif, but ImageTk.PhotoImage does not have a format parameter, which I need.

Here's an example of what I have:

import tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()
canvas = tk.Canvas(root, width = 500, height = 500)
image = Image.open("images.gif").resize((64, 64))
imagetk = ImageTk.PhotoImage(image)
canvas.create_image(250, 250, image=imagetk)
canvas.pack()
root.mainloop()

And here is what I would need:

import tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()
canvas = tk.Canvas(root, width = 500, height = 500)
image = Image.open("images.gif").resize((64, 64))
imagetk = ImageTk.PhotoImage(file=image, format=f"gif -index {anyNum}")
canvas.create_image(250, 250, image=imagetk)
canvas.pack()
root.mainloop()

ImageTk.PhotoImage does not have format parameter and Tkinter has no resize function (at least that I could find)

Thanks!

CodePudding user response:

There is no 'file' param, use 'image' instead:

imagetk = ImageTk.PhotoImage(image=image, format=f"gif -index {anyNum}")

CodePudding user response:

You can use PIL.Image.seek(n) to get the required frame inside the GIF image:

...
image = Image.open("images.gif")
image.seek(1) # seek to second frame in GIF
resized = image.resize((64, 64))
imagetk = ImageTk.PhotoImage(resized)
canvas.create_image(250, 250, image=imagetk)
...
  • Related