首页 > 代码库 > python之tk简单学习之一个简单的钟表效果
python之tk简单学习之一个简单的钟表效果
# -*- coding: utf-8 -*-
# python:2.x
__author__ = ‘Administrator‘
#TK实现一个秒表效果
#目的:是为了简单学习下TK
from time import *
from Tkinter import *
class StopWatch(Frame):
mesc=50
def __init__(self,parent=None,**kw):
Frame.__init__(self,parent,kw)
self.__start=0.0
self._elapsedtime=0.0
self._running=False
self.timerstr=StringVar()
self.makeWidgets()
def makeWidgets(self):
#制作时间标签
l=Label(self,textvariabke=self.timerstr)
self._steTime(self._elapsedtime)
l.pack(fill=X,expand=NO,pady=2,padx=2)
def _update(self):
‘‘‘用逝去的时间更新标签‘‘‘
self._elapsedtime=time()-self.__start
self._setTime(self._elapsedtime)
self._timer=self.after(self.mesc,self._update)
def _setTime(self,elap):
‘‘‘将时间格式改成:分:秒:百分秒‘‘‘
mintes=int(elap/60)
seconds=int(elap-mintes*60.0)
hoesonds=int((elap-mintes*60.-seconds)*100)
self.timerstr.set(‘%02d:%02d:%02d‘%(mintes,seconds,hoesonds))
def Start(self):
‘‘‘启动秒表,如果已经开始则忽略‘‘‘
if not self._running:
self.__start=time()-self._elapsedtime
self._update()
self._running=True
def Stop(self):
‘‘‘停止秒表,如果已经停止则忽略‘‘‘
if self._running:
self.after_cancel(self._timer)
self._elapsedtime=time()-self.__start
self._running=False
def Reset(self):
‘‘‘征调秒表‘‘‘
self.__start=time()
self._elapsedtime=0.0
self._setTime(self._elapsedtime)
if __name__=="__main__":
def main():
tk1=Tk()
sw=StopWatch(tk1)
sw.pack(side=TOP)
Button(tk1,text=‘Start‘,command=sw.Start).pack(side=LEFT)
Button(tk1,text=‘Stop‘,command=sw.Stop).pack(side=LEFT)
Button(tk1,text=‘Reset‘,command=sw.Reset).pack(side=LEFT)
Button(tk1,text=‘Quit‘,command=sw.quit).pack(side=LEFT)
tk1.mainloop()
main()
python之tk简单学习之一个简单的钟表效果