我对python很新,我试图为自己做一个小项目,但我不明白如何使用stop函数中start函数的初始时间变量我可以用它来做数学。这是我目前的代码:
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()
答案 0 :(得分: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()