after_cancel 用作停止方法 [英] after_cancel usage as a stop method

查看:193
本文介绍了after_cancel 用作停止方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to use after_cancel to stop an animated loop in a simple image viewer. I have read the documentation on Tcl, searched here and google, and explored the python subreddits. My error is:

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

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

This occurs in the last line of the following code (please don't kill me for using globals, this project is just an image viewer to display weather forecast products in our office):

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 中的动画循环,请告诉我!

If there is a more appropriate method to stop an animated loop in Tkinter, please let me know!

推荐答案

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

Your code here is not setting a global variable, but a local variable:

callback = None

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

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

Here, callback will remain set to None, and so your root.after_cancel(callback) is equivalent to root.after_cancel(None), which TK doesn't like. Try changing your animate function to:

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

免责声明:我同意 Kevin 的观点,全局变量会迅速繁殖并开启它们的主人,因此请使用类.然后变量被锁定,无法找到你.

Disclaimer: I agree with Kevin, globals multiply rapidly and turn on their master, so use a class. The variables are then locked up and can't get you.

这篇关于after_cancel 用作停止方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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