Python学习笔记(5)Timer

发布时间:2019-09-13 09:25:16编辑:auto阅读(1745)

    下面的笔记内容来自coursera上的Python公开课


    A good program design principle:

    I have an update handler that handles changing the message, and
    I have a tick handler that handles changing the position of the text and 
    I have a draw handler that simply draws whatever message at whatever position.
    These things can run at completely different rates, alright? 
    The draw handler runs at 60 times a second, and
    The tick handle runs once every two seconds, and
    The update handle runs only whenever you type touch it, okay? 
    But it still all works together nicely to give us this interesting interactive application. 

    例1 Simple "screensaver" program

    # Import modules
    import simplegui
    import random
    
    # Global state
    message = "Python is Fun!"
    position = [50, 50]
    width = 500
    height = 500
    interval = 2000
    
    # Handler for text box
    def update(text):
        global message
        message = text
       
    # Handler for timer
    def tick():
        x = random.randrange(0, width)
        y = random.randrange(0, height)
        position[0] = x
        position[1] = y
    
    # Handler to draw on canvas
    def draw(canvas):
        canvas.draw_text(message, position, 36, "Red")
    
    # Create a frame
    frame = simplegui.create_frame("Home", width, height)
    
    # Register event handlers
    text = frame.add_input("Message:", update, 150)
    frame.set_draw_handler(draw)
    timer = simplegui.create_timer(interval, tick)
    
    # Start the frame animation
    frame.start()
    timer.start()
    

    例2 timer 设定了interval后如何改变interval呢

    #下面这样改可以吗?
    import simplegui
    
    def timer_handler():
        print "timer called"
    
    timer = simplegui.create_timer(50, timer_handler)
    timer.start()
    
    timer = simplegui.create_timer(1000, timer_handler)
    timer.start()
    上面代码中,timer的interval企图从50 milisecond变化为1second(1000 milisecond)。
    但是运行时发现,其实这个改动并没有生效。 
    正确的改动interval的方法是这样的:

    …
    timer.stop()
    timer = simplegui.create_timer(1000, timer_handler)
    timer.start() 
    




关键字