如何使用tkinter测量python中按下按钮之间的时间



我对python很陌生,我正在尝试为自己做一个小项目,但我不知道如何在停止函数中使用起始函数中的初始时间变量,我可以用它来做数学运算。这是我目前的代码:

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()

您的函数需要就共享数据的公共位置达成一致。对于这个简单的示例,模块的全局名称空间是一个不错的选择。你所需要做的就是将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()