示例Python Timer程序

时间:2014-08-26 09:33:43

标签: python python-2.7 tkinter

我试图在Tkinter python中执行一个计时器功能,我想在计时器事件中连续调用一个方法。

我的程序是普通的子类,它不包含root或master,因为我将master类分开,所以我在努力编写after函数,是否可以在没有root的情况下编写after函数?由于调用tk 会显示不需要的tk窗口,我只是想要查看我的计时器事件输出 Python shell,有可能吗?

class App():

    def __init__ (self): 

        self.timer_count = 0

        for Test in range(4):
           self.update_clock()


    def update_clock(self):

        self.timer_count+= 1
        print self.timer_count

        self.after(100, self.execute)  # Is it possible?
        #                                Can timer work without any root instance?
        #
        #self.root.after(100, self.update_clock)


App_Obj = App()

2 个答案:

答案 0 :(得分:0)

Tkinter可以做,但请记住,调度以不同的方式工作

Tkinter是一个面向GUI的框架,内置了很多功能。

(Python本身允许您独立于Tkinter设计内容。)

可以设置基于Tkinter端的基于计时器的事件(s),但如上所述,计时器的用户端控制 避免 (没有合理的近实时系统将允许用户去稳定,阻止越少,代码执行流程......)

因此。 Tkinter调度工具基本上就是这些:

aTkScheduledEVENTid = <aTkRootWidget>.after( msecsAfter, aFun2Bcalled = None, *args )
# use
# for deterministic / set wait-time

aTkDeferredEVENTid  = <aTkRootWidget>.after_idle( aFun2Bcalled = None, *args )
# use
# for non-deterministic / deferred till <SIG_IDLE> state of the GUI control-loop

<aTkRootWidget>.after_cancel( { aTkScheduledEVENTid | aTkDeferredEVENTid } )
# use
# upon a need to **cancel**/re-schedule a set execution

独奏魔法

预定的函数调用只执行一次,因此再次重复调度任务是很常见的。#34;内部&#34;被调用的函数,用于重新启动下一个基于计时器的函数调用的注册。

亚瑟已经在上面发布了一个链接到一个整洁的布莱恩奥克利的代码片段。

添加技巧可以帮助您在真实负载下阅读Tkinter 计时的真实可塑性。

(某些平台在[msec] -s)下不显示时间分辨率

class App():                            # Bryan Oakley, in http://stackoverflow.com/a/2401181/3666197
    def __init__( self ):
        self.root = tk.Tk()
        self.label = tk.Label( text = "init" )
        self.label.pack()
        self.update_clock()             # inital call to set a scheduled execution
        self.root.lower()               # OP.Edit: hide the Tk-window, as wanted
        self.root.mainloop()

    def update_clock( self ):
        # \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
        #
        # DEMO to show real plasticity of the Tkinter scheduler timing(s)
        #
        print time.time()               # show real activation timestamp w [msecs]
        #
        # /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
        now = time.strftime( "%H:%M:%S" )
        self.label.configure( text = now )
        self.root.after( 1000,         # re-instate next scheduled call, theoretically after given delay
                         self.update_clock
                         )

答案 1 :(得分:0)

import time

time.clock() #To start timing

#Your code here

timing = time.clock() #Returns a float ex. 0.05
                      #this is the time from start to finish in ms