Home > Back-end >  Python tkinter time delay before placing/ removing images
Python tkinter time delay before placing/ removing images

Time:10-02

I have created a python tkinter program, where I want to display a series of images on a window, where the image changes every 6 seconds. When I use the code below, the whole program freezes for the entire 6 seconds.

loopey = "Fal"
   
while loopey == "Fal":
    time.sleep(6)
    menupic.place_forget()
    menupic2.place(x=602,y=180)
    home.update()
    time.sleep(6)
    menupic2.place_forget()
    menupic.place(x=602,y=180)
    home.update()

I also tried to use the after() function, but had the same issue.

def deletion(thing):
    thing.place_forget()


while True:
    home.after(6000, deletion(menupic))
    menupic2.place(x=602,y=180)
    home.update()
    home.after(6000, deletion(menupic2))
    menupic.place(x=602,y=180)
    home.update()

CodePudding user response:

I would do it like this:

from tkinter import *
from PIL import Image, ImageTk
from random import randint
import numpy as np


def place_image():
    npimg = np.zeros([100,100,3],dtype=np.uint8)
    npimg.fill(randint(0, 255))
    pilimg = Image.fromarray(npimg)
    tkimg = ImageTk.PhotoImage(pilimg)
    label.img = tkimg
    label.configure(image=tkimg)
    home.after(6000, place_image)

home = Tk()

label = Label(home, text="test")
label.place(x=0, y=0)

home.after(6000, place_image)
home.mainloop()

If you use after() also in the function you can still interact with the window. It wil still loop trought every 6 seconds.

  • Related