gpt4 book ai didi

python - 我想限制 Tkinter 回调运行的频率

转载 作者:行者123 更新时间:2023-12-01 06:16:15 24 4
gpt4 key购买 nike

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

我有一个用于搜索的 Entry 小部件,结果会转到列表框。我希望结果随着用户输入而更新,因此我进行了如下回调:

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

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

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

最佳答案

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

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 函数即可。

关于python - 我想限制 Tkinter 回调运行的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3232748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com