0

Im currently trying to change an image in a tkinter label widget by using a binding to the return key. After pressing the return key I would like the image to change to "im2", then wait for 2 seconds and change again to "im3". The code I use so far is:

window = tk.Tk()
window.title("Testwindow")
window.geometry("800x800")
window.configure(background='grey')

# images
im1_path = "im1.gif"
im2_path = "im2.gif"
im3_path = "im3.gif"
im1 = ImageTk.PhotoImage(Image.open(im1_path))
im2 = ImageTk.PhotoImage(Image.open(im2_path))
im3 = ImageTk.PhotoImage(Image.open(im3_path))

panel = tk.Label(window, image = im1)
panel.pack(side = "bottom", fill = "both", expand = "yes")

def callback(e):
    panel.configure(image = im2)
    panel.image = im2

    time.sleep(2)

    panel.configure(image = im3)
    panel.image = im3

window.bind("<Return>", callback)
window.mainloop()

But instead of changing the image twice it is only changed once to "im3" 2 seconds after pressing return, so somehow the first change is not displayed. Does anyone know why?

BStadlbauer
  • 1,287
  • 6
  • 18
  • Changes are not reflected in the UI so long as it is executing your code. Updates only happen in `mainloop()`. – msw Jun 12 '16 at 13:36
  • 1
    Also see http://stackoverflow.com/questions/30284270/why-does-time-sleep-pause-tkinter-window-before-it-opens and http://stackoverflow.com/questions/33175457/time-sleep-equivalent-on-tkinter – PM 2Ring Jun 12 '16 at 13:36
  • @PM2Ring, Thanks alot! – BStadlbauer Jun 12 '16 at 13:41
  • 1
    You may also find this example helpful: http://stackoverflow.com/a/32766256/4014959 – PM 2Ring Jun 12 '16 at 13:47

1 Answers1

5

time.sleep() won't work here as it stops the execution of the program, you'll have to use after...and its also a bad practice to use sleep in GUI programming.

root.after(time_delay, function_to_run, args_of_fun_to_run)

So in your case it'll like

def change_image():
    panel.configure(image = im3)
    panel.image = im3

and in your callback function

def callback(e):
    panel.configure(image = im2)
    panel.image = im2
    #after 2 seconds it'll call the above function
    window.after(2000, change_image)
hashcode55
  • 5,622
  • 4
  • 27
  • 40