如何在 tkinter 中的给定时间后运行函数? [英] How to run a function after a given amount of time in tkinter?

查看:53
本文介绍了如何在 tkinter 中的给定时间后运行函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在 tkinter 的画布上有一张 .gif 图片.我想让这张照片变成另一张照片……但只有 3 秒.并恢复到原始图片.

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.

推荐答案

Tkinter 小部件有一个名为 after 的方法,可用于在指定的时间段后运行函数.要创建一个图像,然后在三秒钟后更改它,您可以执行以下操作:

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

这篇关于如何在 tkinter 中的给定时间后运行函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆