当前位置:   article > 正文

python怎样使用_python – tkinter:如何使用after方法

python after

你需要给出一个在时间延迟之后被调用的函数作为第

after的第二个参数:

after(delay_ms, callback=None, *args)

Registers an alarm callback that is called after a given time.

那么你真正想做的就是这样:

tiles_letter = ['a', 'b', 'c', 'd', 'e']

def add_letter():

rand = random.choice(tiles_letter)

tile_frame = Label(frame, text=rand)

tile_frame.pack()

root.after(500, add_letter)

tiles_letter.remove(rand) # remove that tile from list of tiles

root.after(0, add_letter) # add_letter will run as soon as the mainloop starts.

root.mainloop()

您还需要通过重复调用回调函数之后的调用再次调用该函数,因为只执行给定函数一次.文档中也提到了这一点:

The callback is only called once for each call to this method. To keep

calling the callback, you need to reregister the callback inside

itself

请注意,您的示例将在您耗尽tile_letter中的所有条目后立即抛出异常,因此您需要更改逻辑以处理该情况,无论您想要哪种方式.最简单的事情是在add_letter的开头添加一个检查,以确保列表不为空,只要返回:

def add_letter():

if not tiles_letter:

return

rand = random.choice(tiles_letter)

tile_frame = Label(frame, text=rand)

tile_frame.pack()

root.after(500, add_letter)

tiles_letter.remove(rand) # remove that tile from list of tiles

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/892403
推荐阅读
相关标签
  

闽ICP备14008679号