2016-01-08 103 views
3

我對python很陌生,我正在嘗試爲自己做一個小項目,但我不明白如何在stop函數中使用start函數的初始時間變量,在那裏我可以用它做數學運算。這是我目前的代碼:如何測量按下python中的按鈕與tkinter之間的流逝時間?

import time 
import Tkinter 
import tkMessageBox 

top = Tkinter.Tk() 

def start_time(): 
    tkMessageBox.showinfo("Timer", "The timer will now begin") 
    initial = time.time() 
    return initial 

def stop_time(initial): 
    final = time.time() 
    tkMessageBox.showinfo("Timer", final - initial) 

Start = Tkinter.Button(top, text ="Start", command = start_time) 
Stop = Tkinter.Button(top, text ="Stop", command = stop_time) 
Start.pack() 
Stop.pack() 
top.mainloop() 

回答

2

您的功能需要就共享數據的共同位置達成一致。對於這個簡單的例子,模塊的全局命名空間是一個不錯的選擇。您只需將global initial添加到更新它的函數中即可。對於較大的項目,您可能會移動到包含變量和更新它的函數的對象,但這對您的目標很合適。

import time 
import Tkinter 
import tkMessageBox 

initial = 0 

top = Tkinter.Tk() 

def start_time(): 
    global initial 
    tkMessageBox.showinfo("Timer", "The timer will now begin") 
    initial = time.time() 
    return initial 

def stop_time(): 
    # you could check for initial == 0 and display an error 
    final = time.time() 
    tkMessageBox.showinfo("Timer", final - initial) 

Start = Tkinter.Button(top, text ="Start", command = start_time) 
Stop = Tkinter.Button(top, text ="Stop", command = stop_time) 
Start.pack() 
Stop.pack() 
top.mainloop()