Python tkinter time.sleep() [英] Python tkinter time.sleep()

查看:46
本文介绍了Python tkinter time.sleep()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么当我运行我的代码时,它会先休眠 3 秒,然后执行 'label' .lift() 并更改文本?这只是程序中许多功能中的一个.我希望标签上显示从 3...2...1... 开始",并且数字会在经过一秒后发生变化.

How come when I run my code, it will sleep for 3 seconds first, then execute the 'label' .lift() and change the text? This is just one function of many in the program. I want the label to read "Starting in 3...2...1..." and the numbers changing when a second has passed.

def predraw(self):
    self.lost=False
    self.lossmessage.lower()
    self.countdown.lift()
    self.dx=20
    self.dy=0
    self.delay=200
    self.x=300
    self.y=300
    self.foodx=self.list[random.randint(0,29)]
    self.foody=self.list[random.randint(0,29)]
    self.fillcol='blue'
    self.canvas['bg']='white'
    self.lossmessage['text']='You lost! :('
    self.score['text']=0
    self.countdown['text']='Starting in...3'
    time.sleep(1)
    self.countdown['text']='Starting in...2'
    time.sleep(1)
    self.countdown['text']='Starting in...1'
    time.sleep(1)
    self.countdown.lower()
    self.drawsnake()

推荐答案

这样做是因为小部件中的更改仅在 UI 进入事件循环时才可见.每次调用 sleep 后,您不允许屏幕更新,因此在更改任何内容之前它似乎在休眠三秒钟.

It does this because changes in widgets only become visible when the UI enters the event loop. You aren't allowing the screen to update after calling sleep each time, so it appears that it's sleeping three seconds before changing anything.

一个简单的解决方法是在调用 time.sleep(1) 之前立即调用 self.update(),但更好的解决方案是不调用 sleep 根本没有.你可以这样做,例如:

A simple fix is to call self.update() immediately before calling time.sleep(1), though the better solution is to not call sleep at all. You could do something like this, for example:

self.after(1000, lambda: self.countdown.configure(text="Starting in...3"))
self.after(2000, lambda: self.countdown.configure(text="Starting in...2"))
self.after(3000, lambda: self.countdown.configure(text="Starting in...1"))
self.after(4000, self.drawsnake)

通过以这种方式使用 after,您的 GUI 在等待时间内保持响应,并且您不必频繁调用 update.

By using after in this manner, your GUI remains responsive during the wait time and you don't have to sprinkle in calls to update.

这篇关于Python tkinter time.sleep()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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