【问题标题】:I want to limit how often a Tkinter callback is run我想限制 Tkinter 回调的运行频率
【发布时间】:2011-03-15 01:10:23
【问题描述】:

我正在用 Tkinter 编写我的第一个 GUI 程序(实际上也是第一个 Python 程序)。

我有一个用于搜索的条目小部件,结果进入一个列表框。我希望结果随着用户输入而更新,所以我做了一个这样的回调:

search_field.bind("<KeyRelease>", update_results)

问题是连续多次更新搜索。由于结果将来自数据库查询,因此会产生大量不必要的流量。我真正想要的是它每隔一秒左右更新一次,或者在用户停止输入后等待一秒钟然后搜索。最简单的方法是什么? 谢谢

更新:这很适合我描述的内容,但现在我意识到我还需要在用户停止输入后触发更新。否则,最后几个字符永远不会包含在搜索中。我想我必须不接受答案才能回到问题列表中......

【问题讨论】:

    标签: python user-interface events tkinter


    【解决方案1】:

    一个很好的方法是一个简单的缓存装饰器:

    import time
    def limit_rate( delay=1.0 ):
        """ produces a decorator that will call a function only once per `delay` """
        def wrapper( func ): # the actual decorator
            cache = dict( next = 0 ) # cache the result and time
            def limited( *args, **kwargs):
                if time.time() > cache['next']: # is it time to call again
                    cache['result'] = func( *args, **kwargs) # do the function
                    cache['next'] = time.time() + delay # dont call before this time
                return cache['result']
            return limited
        return wrapper
    

    它的工作原理是这样的:

    @limit_rate(1.5)
    def test():
        print "Called test()"
        time.sleep( 1 )
        return int(time.time())
    
    print [test() for _ in range(5)] # test is called just once
    

    您只需将此装饰器添加到某处并用它装饰您的 update_results 函数。

    【讨论】:

      【解决方案2】:

      想通了。我使用 any_widget.after(delay_in_ms, function) 延迟调用装饰函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-25
        • 2014-11-02
        • 1970-01-01
        • 2020-12-21
        • 2011-01-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多