【问题标题】:Python: Tkinter - One animation stops when the other beginsPython:Tkinter - 一个动画在另一个动画开始时停止
【发布时间】:2014-01-15 20:00:39
【问题描述】:
for plusOneFrames in range(0, 25):
    xxUL = xxUL + 0  
    yyUL = yyUL - 5

    myText = screen.create_text( xxUL, yyUL, text = "+1", font = "Arial 25", fill = "black"  )
    screen.update()
    sleep(0.05)
    screen.delete( myText )
screen.delete( myText )

所以基本上,每当用户点击时,它就会使 +1 浮动,但每当一个上升并且我再次点击时,已经上升的 +1 会停在它的位置并就在那里。如果我再次单击它会执行相同的操作,直到出现数百个。我怎样才能让它永远不会停止动画,即使它全部在一个 for 循环中?

【问题讨论】:

标签: python tkinter


【解决方案1】:

你不能在 Tkinter 回调中间使用sleep 而不使整个程序停止运行。毕竟,这正是sleep(0.05) 的意思:让整个程序停止运行0.05 秒。

而且不仅仅是sleep——不管这个函数做什么,当它运行时,它就是运行的代码;没有其他代码可以运行,因此您的 UI 会被冻结。

有两种基本的解决方案:

  • 更改您的函数,使其执行动画的一个步骤,安排下一步在 0.05 秒内作为回调运行,然后返回。
  • 使用后台线程。

第二个可能看起来更简单,但不幸的是,在多线程应用程序中使用 Tkinter 有点痛苦。所以,让我们做第一个。像这样的:

def nextframe(i):
    nonlocal xxUL, yyUL
    xxUL = xxUL + 0  
    yyUL = yyUL - 5

    myText = screen.create_text( xxUL, yyUL, text = "+1", font = "Arial 25", fill = "black"  )
    screen.update()
    screen.delete( myText )
    i += 1
    if i != 25:
        screen.after(0.05, lambda: nextframe(i))
    else:
        screen.delete( myText )

nextframe(0)

(我不知道这里的确切细节是否适用于您的实际代码——事实上,如果您的代码没有使用 Python 3.0+,或者您没有在另一个函数中本地执行此操作,我知道它会成功不行。但是由于你没有展示你的实际代码,我不得不做出一些猜测,希望你能理解如何适应它。)

请参阅Why your GUI app freezes 了解更多详情,或 google 了解有关事件循环或事件驱动编程的优秀教程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多