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

回眸只為那壹抹淺笑 提交于 2019-12-31 03:25:09

问题


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:


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"))


来源:https://stackoverflow.com/questions/20529533/how-to-run-a-function-after-a-given-amount-of-time-in-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!