How to run a function after a given amount of time

2019-02-27 13:17发布

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.

1条回答
祖国的老花朵
2楼-- · 2019-02-27 13:59

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"))
查看更多
登录 后发表回答