问题
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