DanSuh
DanSuh

Reputation: 51

How to run a function after a given amount of time in tkinter?

So I have a .gif picture on a canvas in tkinter. I want this picture to change to another picture...but only for 3 seconds. and for it revert back to the original picture.

def startTurn(self):
    newgif = PhotoImage(file = '2h.gif')
    self.__leftImageCanvas.itemconfigure(self.__leftImage, image = newgif)
    self.__leftImageCanvas.image = newgif
    while self.cardTimer > 0:
        time.sleep(1)
        self.cardTimer -=1       
    oldgif = PhotoImage(file = 'b.gif')
    self.__leftImageCanvas.itemconfigure(self.__leftImage, image = oldgif)
    self.__leftImageCanvas.image = oldgif 

this is a first attempt after a quick view of the timer. i know that this code does not make sense, but before i keep mindlessly trying to figure it out, i would much rather have more experienced input.

Upvotes: 2

Views: 772

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385970

Tkinter widgets have a method named after which can be used to run a function after a specified period of time. To create an image and then change it three seconds later, you would do something like this:

def setImage(self, filename):
    image = PhotoImage(file=filename)
    self.__leftImageCanvas.itemconfigure(self.__leftImage, image=image)
    self.__leftImageCanvas.image = image

def startTurn(self):
    '''Set the image to "2h.gif", then change it to "b.gif" 3 seconds later'''
    setImage("2h.gif")
    self.after(3000, lambda: self.setImage("b.gif"))

Upvotes: 3

Related Questions