且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在程序在给定的时间空闲之后调用函数

更新时间:2023-10-27 15:40:34

在以下示例中, tick 函数每秒调用一次。 5秒钟后,除非按下键或鼠标按钮1,否则打印消息。

In the following example, the tick function is called every second. After 5 seconds, a message is printed, unless a key or mouse button 1 were pressed.

import time
from Tkinter import *

root = Tk()
running = None

def reset(*ignore): 
    global running
    running = None

def tick(*ignore):
    global running
    if not running:
        running = time.time()
    elif time.time() - running > 5:
        print 'I waited 5 seconds...'
        running = None
    root.after(1000, tick)   

root.after(1000, tick)    
root.bind('<Key>', reset)
root.bind('<Button-1>', reset)
root.mainloop()