Python学习笔记(5)Timer

来源:互联网 发布:linux sort -k 1 编辑:程序博客网 时间:2024/06/07 19:58
下面的笔记内容来自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 modulesimport simpleguiimport random# Global statemessage = "Python is Fun!"position = [50, 50]width = 500height = 500interval = 2000# Handler for text boxdef update(text):    global message    message = text   # Handler for timerdef tick():    x = random.randrange(0, width)    y = random.randrange(0, height)    position[0] = x    position[1] = y# Handler to draw on canvasdef draw(canvas):    canvas.draw_text(message, position, 36, "Red")# Create a frameframe = simplegui.create_frame("Home", width, height)# Register event handlerstext = frame.add_input("Message:", update, 150)frame.set_draw_handler(draw)timer = simplegui.create_timer(interval, tick)# Start the frame animationframe.start()timer.start()

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

#下面这样改可以吗?import simpleguidef 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() 




0 0
原创粉丝点击