Python Tkinter after() 只执行一次 [英] Python Tkinter after() Only Executing Once

查看:63
本文介绍了Python Tkinter after() 只执行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来应该如此简单的事情给我带来了很大的问题.我有一个 Tkinter GUI,我正在尝试定期更新.具体来说,我正在从画布上删除项目并替换它们.作为一个例子,尽管我只是想打印一个证明 after 函数正常工作的语句.当我放置一个按钮并单击它时,一切都很好,但我想使用 after() 函数自动完成它.不过,我没有太多运气让它工作.

Something that seems like it should be so simple is giving me quite an issue. I have a Tkinter GUI that I am trying to update at regular intervals. Specifically I am deleting items off a canvas and replacing them. As an example here though I am just trying to print a statement that proves the after function is working correctly. When I place a button and click it, things work great, but I would like to do it automatically using the after() function. I am not having much luck getting it to work though.

class app():
    def __init__(self, frame):
        self.pad = tk.Canvas(frame)
        self.pad.create_window(10, 10, window=tk.Button(self.pad,command=update)
        self.pack(fill="both")

        #More Stuff

        #Neither one worked
        frame.after(1000,update)
        #self.pad.after(1000,update)

    def update(self):
        print "Updating"
        #More Stuff

if __name__=="__main__":
    root = tk.TK()
    app(root)
    root.mainLoop()

当然这不是完整的代码,但希望它有足够的意义来了解我正在尝试做什么.因此,当我单击按钮时,会看到正在更新"字样.但是当我使用 after 函数时,它在开始时出现一次,再也不会出现.我也是 Python 2.4.4 版本,别以为我没有发言权哈哈.感谢您的任何帮助!

Of course this isn't the complete code, but hopefully it makes enough sense to see what I am trying to do. So when I click the button I see the words "Updating" appear. But when I use the after funciton, it appears once at the start and never again. I am also on Python version 2.4.4, don't judge I have no say in it haha. Thanks for any and all help!

推荐答案

update 结束时调用 after :

Place a call to after at the end of update:

def __init__(self, frame):       
    self.frame = frame
    ...
    self.frame.after(1000, self.update)

def update(self): 
    ...
    self.frame.after(1000, self.update)

这是after 的工作方式.它只将回调(例如 self.update)排队一次.根据文档:

This is the way after works. It only queues the callback (e.g. self.update) once. Per the docs:

每次调用此方法只调用一次回调.到不断调用回调,需要在里面重新注册回调本身

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

这篇关于Python Tkinter after() 只执行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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