nedak96
nedak96

Reputation: 5

Using time module in tkinter module

from tkinter import *

import time

root = Tk()

class Cycle(Frame):

    def __init__(self):
        Frame.__init__(self)
        self.master.title("Cycle")
        self.grid()
        self.__pic1 = PhotoImage(file = "Bar.png")
        self.__pic2 = PhotoImage(file = "bell.gif")
        self.__pic1Label = Label(image = self.__pic1)
        self.__pic2Label = Label(image = self.__pic2)
        self.__pic1Label.grid(row=0, column=0)
        time.sleep(1)
        self.__pic2Label.grid(row=0, column=0)

Cycle()

Instead of displaying the first image, waiting a second, and displaying the second image over the first one, it waits a second and then the box pops up and displays both at the same time.

Upvotes: 0

Views: 822

Answers (1)

user2555451
user2555451

Reputation:

time.sleep cannot be called in the same thread as the Tkinter event loop is operating in. It will block Tkinter's loop and thereby cause the program to freeze.

You should be using the .after method to schedule the operation to run in the background after 1000 milliseconds (or one second):

self.after(1000, lambda: self.__pic2Label.grid(row=0, column=0))

Also, I used a lambda expression for the sake of brevity. However, .after accepts normal function objects as well:

self.after(1000, self.my_method)

Upvotes: 2

Related Questions