为什么当我运行我的代码时,它会先休眠 3 秒,然后执行“标签”.lift() 并更改文本?这只是该程序中众多功能中的一个。我希望标签显示为“从 3...2...1... 开始”,并且数字会在一秒过去后发生变化。
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 后更新屏幕,因此看起来它在更改任何内容之前正在休眠三秒钟。
一个简单的修复方法是在调用 time.sleep(1) 之前立即调用 self.update(),但更好的解决方案是不调用 sleep 完全没有。你可以这样做,例如:
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。
