python交互式图形编程实例(三)
本文实例为大家分享了python交互式图形编程实例的第三部代码,供大家参考,具体内容如下
#!/usr/bin/envpython3
#-*-coding:utf-8-*-
#时钟
fromturtleimport*
fromdatetimeimport*
defSkip(step):
penup()
forward(step)
pendown()
defmkHand(name,length):
#注册Turtle形状,建立表针Turtle
reset()
Skip(-length*0.1)
begin_poly()#开始记录画笔坐标
forward(length*1.1)#画笔向前移动length*1.1
end_poly()#结束记录画笔坐标
handForm=get_poly()#记录画笔起始和结束坐标位置(一个元组数据)
register_shape(name,handForm)#注册这个形状
defInit():
globalsecHand,minHand,hurHand,printer
mode("logo")#重置Turtle指向北
#建立三个表针Turtle并初始化
mkHand("secHand",125)
mkHand("minHand",130)
mkHand("hurHand",90)
secHand=Turtle()
secHand.shape("secHand")
minHand=Turtle()
minHand.shape("minHand")
hurHand=Turtle()
hurHand.shape("hurHand")
forhandinsecHand,minHand,hurHand:
hand.shapesize(1,1,3)
hand.speed(0)
#建立输出文字Turtle
printer=Turtle()
printer.hideturtle()#隐藏画笔
printer.penup()
defSetupClock(radius):
#建立表的外框
reset()
pensize(7)#画笔大小
foriinrange(60):
Skip(radius)#画笔抬起,向前移动“radius”具体
ifi%5==0:
forward(20)#如果能被5整除,就向前移动20
Skip(-radius-20)#画笔再回退到原位置
else:
dot(5)#画一个5个像素的点
Skip(-radius)#画笔再回退到原位置
right(6)#每次循环向右移动6个弧度
defWeek(t):
week=["星期一","星期二","星期三",
"星期四","星期五","星期六","星期日"]
returnweek[t.weekday()]#返回当前是星期几
defDate(t):
y=t.year
m=t.month
d=t.day
return"%s%d%d"%(y,m,d)#返回当前日期
defTick():
#绘制表针的动态显示
t=datetime.today()
second=t.second+t.microsecond*0.000001#精确到微秒
minute=t.minute+second/60.0#精确的秒
hour=t.hour+minute/60.0#精确到分钟
secHand.setheading(6*second)#秒针设定的角度一圈360度,一圈60秒360/60=6
minHand.setheading(6*minute)#分针设定的角度一圈360度,一圈60分钟360/60=6
hurHand.setheading(30*hour)#时针设定的角度一圈360度,一圈12小时360/12=30
tracer(False)#取消动画,字直接打在画布上
printer.forward(65)
printer.write(Week(t),align="center",
font=("Courier",14,"bold"))
printer.back(130)
printer.write(Date(t),align="center",
font=("Courier",14,"bold"))
printer.home()
tracer(True)#开启动画
ontimer(Tick,100)#100ms后继续调用tick
defmain():
tracer(False)
Init()#把表针画出来
SetupClock(160)#把表盘画出来
tracer(True)
Tick()#让表针动起来,文字写上去
mainloop()
if__name__=="__main__":
main()
#!/usr/bin/envpython3
#-*-coding:utf-8-*-
#键盘值查询
fromtkinterimport*
root=Tk()
#创建一个框架,在这个框架中响应事件
frame=Frame(root,width=256,height=256)
defcallBack(event):
print(event.keysym)
frame.bind("",callBack)
frame.pack()
#当前框架被选中,意思是键盘触发,只对这个框架有效
frame.focus_set()
mainloop()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。