【问题标题】:after_cancel usage as a stop methodafter_cancel 用作停止方法
【发布时间】:2014-12-05 15:44:35
【问题描述】:

我正在尝试使用 after_cancel 在简单的图像查看器中停止动画循环。我已经阅读了关于 Tcl 的文档,在这里和谷歌搜索,并探索了 python subreddits。我的错误是:

TclError: wrong # args: should be "after cancel id|command"

这发生在以下代码的最后一行(请不要因为使用全局变量而杀了我,这个项目只是一个图像查看器,用于显示我们办公室的天气预报产品):

n_images = 2
images = [PhotoImage(file="filename"+str(i)+".gif") for i in range(n_images)]
current_image = -1

def change_image():
    displayFrame.delete('Animate')
    displayFrame.create_image(0,0, anchor=NW,
                        image=images[current_image], tag='Animate')
    displayFrame.update_idletasks() #Force redraw

callback = None

def animate():
    forward()
    callback = root.after(1000, animate)

def forward():
    global current_image
    current_image += 1
    if current_image >= n_images:
        current_image = 0
    change_image()

def back():
    global current_image
    current_image -= 1
    if current_image < 0:
        current_image = n_images-1
    change_image()

def stop():
    root.after_cancel(callback)

如果有更合适的方法来停止 Tkinter 中的动画循环,请告诉我!

【问题讨论】:

  • stop 在哪里被调用?
  • 在回应您对我对这个问题的上一版本的回答stackoverflow.com/questions/27297814/… 的评论时,我说动画需要@9​​87654325@ 添加并编辑到我的回答中。

标签: python python-2.7 tkinter pillow


【解决方案1】:

使用after_cancel 的替代方法是,您可以使用额外的全局值来跟踪循环是否应该继续。

should_continue_animating = True

def animate():
    forward()
    if should_continue_animating:
        root.after(1000, animate)

def stop():
    global should_continue_animating
    should_continue_animating = False

额外的设计提示:将所有函数放入单个类的方法中可能会很有用。然后你会有self.current_imageself.should_continue_animating 而不是全局值。如果您想同时为多个图像制作动画,这将是一个不错的设计选择。

【讨论】:

    【解决方案2】:

    你这里的代码不是设置全局变量,而是设置局部变量:

    callback = None
    
    def animate():
        forward()
        callback = root.after(1000, animate)
    

    在这里,callback 将保持设置为 None,因此您的 root.after_cancel(callback) 等同于 root.after_cancel(None),这是 TK 不喜欢的。尝试将您的 animate 函数更改为:

    def animate():
        global callback
        forward()
        callback = root.after(1000, animate)
    

    免责声明:我同意 Kevin 的观点,全局变量快速繁殖并开启其主人,所以使用一个类。然后变量被锁定,无法获取您。

    【讨论】:

    • 很好,我担心还有其他我错过的问题。
    猜你喜欢
    • 2021-09-18
    • 2018-04-29
    • 2017-04-05
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多