Python学习笔记(5)Timer

本文探讨了Python编程中良好的设计原则,并通过一个简单的‘屏幕保护程序’示例,展示了如何使用Timer进行定时操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面的笔记内容来自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() 




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值