How to set the speed of a gif in Python - python

i am using Python and I inserted a gif in my project. The issue is when i start the application the gif in the application runs in different way than orginal gif. I think that the frames in the gif are run in different speed. How to set the original gif?
I imported PIL and tkinter. This is the code:
import threading
from tkinter import *
from PIL import Image, ImageTk, ImageSequence
def play_gif():
global img
img = Image.open("Gifs/beaming_face_with_smiling_eyes.gif")
lbl = Label(root)
lbl.place(x = 0, y = 0)
for img in ImageSequence.Iterator(img):
img = ImageTk.PhotoImage(img)
lbl.config(image = img)
root.update()
def exit():
root.destroy()
threading.Timer(3.0, play_gif).start()
Button(root,text = "exit", command=exit).place(x = 450, y = 300)
root.mainloop()

Related

How to change tkinter label background image on button click

img= (Image.open("image/frame.png")).resize((240, 240), Image.ANTIALIAS)
new_image = ImageTk.PhotoImage(img)
panel = tk.Label(right_workspace, image=new_image)
panel.pack(side = "top", fill = "none", expand = "none", pady=29)
Thats my label with its image background. Now how can I change this background by a function so everytime my program generates a new qrcode from an input it replaces previous background?
I gather what you're doing, but please leave a minimum reproducible code in future.
Here's an example of how you'd create a functioning tkinter GUI that displays a random image from a list of QR .pngs in a set folder when the button is pressed. You should be able to adapt this to the other part of your program that generates the QR code for you.
import tkinter as tk
from PIL import Image, ImageTk
import os
import random
class QrGenerator:
def __init__(self, main):
self.main = main
self.panel = tk.Label(main)
self.panel.grid(row=0, column=0)
self.button = tk.Button(main, text='Random QR', command=self.random_qr)
self.button.grid(row=1, column=0)
def random_qr(self):
fp = r'C:\Filepath\QR Codes Folder'
os.chdir(fp)
qr_code = random.choice(os.listdir(fp))
print(qr_code)
img = Image.open(qr_code).resize((240, 240), Image.ANTIALIAS)
new_image = ImageTk.PhotoImage(img)
self.panel.configure(image=new_image)
self.panel.image = new_image
if __name__ == '__main__':
root = tk.Tk()
gui = QrGenerator(root)
root.mainloop()

How can I remove blur / blur and rotate at the same time?

I am a beginner in python and learning about PIL and tkinter.
Now what I am trying is to edit a image and I am struggling from blur and rotate.
When I blur an image, I cannot get rid of it without rotating it. (I want to make a button to on/off blur)
And if I blur/rotate an image,
Another one doesn't work at the same time.
How can I solve this problem? here is my code
import tkinter as tk
from PIL import Image, ImageTk, ImageFilter
from tkinter import filedialog as fd
img=None
tk_img=None
angle=0
def open():
global img, tk_img
filename=fd.askopenfilename()
img=Image.open(filename)
tk_img=ImageTk.PhotoImage(img)
canvas.create_image(250,250,image=tk_img)
window.update()
def quit():
window.destroy()
def image_rotate():
global img,tk_img,angle
angle=angle+45
tk_img=ImageTk.PhotoImage(img.rotate(angle))
canvas.create_image(250,250,image=tk_img)
window.update()
def image_blur():
global img,tk_img
tk_img=ImageTk.PhotoImage(img.filter(ImageFilter.BLUR))
canvas.create_image(250,250,image=tk_img)
window.update()
window = tk.Tk() #윈도우 생성
canvas=tk.Canvas(window,width=500,height=500)
canvas.pack()
menubar = tk.Menu(window) #메뉴바 생성
filemenu = tk.Menu(menubar) #파일메뉴를 메뉴바에 달아줌
filemenu.add_command(label="picture", command=open)
filemenu.add_command(label="exit", command=quit)
menubar.add_cascade(label="파일", menu=filemenu)
imagemenu=tk.Menu(menubar)
imagemenu.add_command(label="rotate",command=image_rotate)
imagemenu.add_command(label="blur",command=image_blur)
menubar.add_cascade(label="movement", menu=imagemenu)
window.config(menu=menubar)
window.mainloop()
The reason is quite obvious, your img object as seen is only defined/updated in open(), so the image will always refer to the original image selected and not the new edited image, so to show the change store it in a new variable and then globalize it.
Also note that you are creating a new canvas image every time you call the function, which is not efficient, so make a single canvas image and then update it each time, inside the function using itemconfig() method.
def open():
global img, tk_img
filename = fd.askopenfilename()
img = Image.open(filename)
tk_img = ImageTk.PhotoImage(img)
canvas.itemconfig('img',image=tk_img) # Update image
def image_rotate():
global tk_img, angle, img
angle += 45 # More pythonic to always use += rather than a = a + 10
img = img.rotate(angle)
tk_img = ImageTk.PhotoImage(img)
canvas.itemconfig('img',image=tk_img) # Update image
angle -= 45
def image_blur():
global tk_img, img
img = img.filter(ImageFilter.BLUR)
tk_img = ImageTk.PhotoImage(img)
canvas.itemconfig('img',image=tk_img) # Update image
canvas = tk.Canvas(window,width=500,height=500)
canvas.create_image(250,250,tag='img') # Create initial canvas object
canvas.pack()
Also take a look at how I formatted your code to make it look more near, follow PEP 8 -- Style Guide for Python Code for more.
You can blur the image using opencv package
import cv2
img = cv2.imread('imagepath')
blurImg = cv2.blur(img,(10,10))
cv2.imshow('blurred image',blurImg)
cv2.waitKey(0)
cv2.destroyAllWindows()
Or u can check the documentation of opencv to blurr the image.
U can also rotate image using opencv
# importing cv2
import cv2
src = cv2.imread(path)
window_name = 'Image'
image = cv2.rotate(src, cv2.ROTATE_90_COUNTERCLOCKWISE)
# Displaying the image
cv2.imshow(window_name, image)
cv2.waitKey(0)

I need help displaying full screen images with tkinter

I am doing a people counter in raspberry pi. I want to display an one image if someone comes in, and another one if someone comes out. Right now i am using the code below (that i took from another question here xd) to change the image that tkinter is displaying. The problem with this is thay it only shows the picture cat.jpg for a second, and then it shows a black screen and nothing happends.
import sys
if sys.version_info[0] == 2: # the tkinter library changed it's name from Python 2 to 3.
import Tkinter
tkinter = Tkinter #I decided to use a library reference to avoid potential naming conflicts with people's programs.
else:
import tkinter
from PIL import Image, ImageTk
import time
def updateRoot(root,imagen):
pilImage = Image.open(imagen)
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
root.geometry("%dx%d+0+0" % (w, h))
root.focus_set()
root.bind("<Escape>", lambda e: (e.widget.withdraw(), e.widget.quit()))
canvas = tkinter.Canvas(root,width=w,height=h)
canvas.pack()
canvas.configure(background='black')
imgWidth, imgHeight = pilImage.size
if imgWidth > w or imgHeight > h:
ratio = min(w/imgWidth, h/imgHeight)
imgWidth = int(imgWidth*ratio)
imgHeight = int(imgHeight*ratio)
pilImage = pilImage.resize((imgWidth,imgHeight), Image.ANTIALIAS)
image = ImageTk.PhotoImage(pilImage)
imagesprite = canvas.create_image(w/2,h/2,image=image)
root.update()
root = tkinter.Tk()
updateRoot(root,"Cat.jpg")
time.timesleep(5)
updateRoot(root,"Dog.jpg")
Before this I used this code
import tkinter
from PIL import Image, ImageTk
from tkinter import ttk
def updateRoot(root,imagen):
image1 = Image.open(imagen)
image2 = ImageTk. PhotoImage(image1)
image_label = ttk. Label(root , image =image2)
image_label.place(x = 0 , y = 0)
root.update()
That works fine, but it's not full screen.
First you should do the followings outside updateRoot():
make root window fullscreen (you can simply use root.attributes('-fullscreen', 1))
bind the <Escape> key
create the canvas and create_image() (you can use Label to do the same thing)
Then just update the image inside updateRoot().
Also you should use after() instead of time.sleep().
Below is an example:
try:
import Tkinter as tkinter
except:
import tkinter
from PIL import Image, ImageTk
def updateRoot(imagen):
# resize the image to fill the whole screen
pilImage = Image.open(imagen)
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
image = ImageTk.PhotoImage(pilImage.resize((w,h)))
# update the image
canvas.itemconfig(imgbox, image=image)
# need to keep a reference of the image, otherwise it will be garbage collected
canvas.image = image
root = tkinter.Tk()
root.attributes('-fullscreen', 1)
root.bind('<Escape>', lambda _: root.destroy())
canvas = tkinter.Canvas(root, highlightthickness=0)
canvas.pack(fill=tkinter.BOTH, expand=1)
imgbox = canvas.create_image(0, 0, image=None, anchor='nw')
# show the first image
updateRoot('Cat.jpg')
# change the image 5 seconds later
root.after(5000, updateRoot, 'Dog.jpg')
root.mainloop()
Fixed your Black issue using labels, try this. i think you still need to resize image to fit screen
import sys
if sys.version_info[0] == 2: # the tkinter library changed it's name from Python 2 to 3.
import Tkinter
tkinter = Tkinter #I decided to use a library reference to avoid potential naming conflicts with people's programs.
else:
import tkinter
from PIL import Image, ImageTk
import time
from tkinter import *
import PIL.Image
def updateRoot(root,imagen):
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
root.geometry("%dx%d+0+0" % (w, h))
root.focus_set()
root.bind("<Escape>", lambda e: (e.widget.withdraw(), e.widget.quit()))
img = PIL.Image.open(imagen)
root.tkimage = ImageTk.PhotoImage(img)
Label(root,image = root.tkimage).place(x=0, y=0, relwidth=1, relheight=1)
root.update()
root = tkinter.Tk()
updateRoot(root,"Cat.jpg")
time.sleep(3)
updateRoot(root,"Dog.jpg")
root.mainloop()

I Cant get an image to be resized and displayed using tkinter

So im trying to make an app that will display images, and the image I have is 1000*1000 but this is way too big, I need a way to resize the image. I've tried using PIL and ImageTK but that didn't work, here's my code so far:
from tkinter import *
app = Tk()
app.title('embeded image')
fname = Canvas(bg = 'black', height=100, width=100)
fname.pack(side=TOP)
image = PhotoImage('Sun.png')
image = image.resize((25, 25), Image.ANTIALIAS)
icon = fname.create_image(image=image)
fname.pack()
app.mainloop()
I've no idea why this doesn't work, im relatively new to Tkinter so sorry if it's obvious.
You mix two differnt class PhotoImage in tkinter which doesn't have resize and PIL.Image which have resize
import tkinter as tk
from PIL import Image, ImageTk
app = tk.Tk()
fname = tk.Canvas(height=200, width=200)
fname.pack()
pil_image = Image.open('Sun.png')
pil_image = pil_image.resize((25, 25), Image.ANTIALIAS)
image = ImageTk.PhotoImage(pil_image)
icon = fname.create_image((0,0), image=image, anchor='nw')
app.mainloop()

How do I place an image (.png) within a `LabelFrame`, and resize it, in Tkinter?

I'm trying to place a .png image within a LabelFrame in a Tkinter window. I imported PIL so .png image types should be supported (right?). I can't seem to get the image to show up.
Here is my revised code:
import Tkinter
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
make_frame = LabelFrame(root, text="Sample Image", width=150, height=150)
make_frame.pack()
stim = "image.png"
width = 100
height = 100
stim1 = stim.resize((width, height), Image.ANTIALIAS)
img = ImageTk.PhotoImage(image.open(stim1))
in_frame = Label(make_frame, image = img)
in_frame.pack()
root.mainloop()
With this code, I got an AttributeError that reads: "'str' has no attribute 'resize'"
#Mickey,
You have to call the .resize method on the PIL.Image object and not the filename, which is a string. Also, you may prefer to use PIL.Image.thumbnail instead of PIL.Image.resize, for reasons described clearly here. Your code was close, but this might be what you need:
import Tkinter
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
make_frame = LabelFrame(root, text="Sample Image", width=100, height=100)
make_frame.pack()
stim_filename = "image.png"
# create the PIL image object:
PIL_image = Image.open(stim_filename)
width = 100
height = 100
# You may prefer to use Image.thumbnail instead
# Set use_resize to False to use Image.thumbnail
use_resize = True
if use_resize:
# Image.resize returns a new PIL.Image of the specified size
PIL_image_small = PIL_image.resize((width,height), Image.ANTIALIAS)
else:
# Image.thumbnail converts the image to a thumbnail, in place
PIL_image_small = PIL_image
PIL_image_small.thumbnail((width,height), Image.ANTIALIAS)
# now create the ImageTk PhotoImage:
img = ImageTk.PhotoImage(PIL_image_small)
in_frame = Label(make_frame, image = img)
in_frame.pack()
root.mainloop()

Categories

Resources