我一直在尝试一个反应测试,问题是当我为定义函数中的时间定义一个变量时,它后来说变量布尔没有定义。我很想知道如何在定义函数中定义time.time()变量。理想的结果是,它应该打印开始和结束时间之间的时间
import turtle
import time
wn = turtle.Screen()
wn.title("Temp")
wn.setup(width=600, height=600 )
wn.tracer(0)
wn.bgcolor("blue")
def temp(x, y):
start = time.time()
wn.onscreenclick(temp2)
wn.onscreenclick(temp)
def temp2(x, y):
end = time.time()
total = end - start
print (total)
wn.mainloop()
以下是具体的错误代码:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\erigo\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:\Users\erigo\AppData\Local\Programs\Python\Python38\lib\turtle.py", line 675, in eventfun
fun(x, y)
File "C:/Users/erigo/PycharmProjects/Reactiontest/Reaction_test.py", line 38, in click
total = end - start
NameError: name 'start' is not defined
在
click(x,y)
方法中有一行ms = end - a
。变量end
已在前一行中定义,但变量a
未在代码中的任何位置定义。 这可能会给您带来错误至于如何创建计时器,我认为您有一个作用域问题,我看到您在方法
clicked()
中创建并启动计时器,但是您想停止它并在方法click()
中计算偏移量,最好的方法是在一个更大的类中,这些函数是方法,计时器是实例变量。但是,只需在这些函数之外使用全局变量,就可以获得相同的结果(尽管这可能不是很好的做法)因此,每当在方法/函数内部定义变量时,就不能从该方法外部访问其值
这就是为什么当您试图访问
start
行中的total = end - start
时,Python解释器不知道什么是start
有几种方法可以解决这个问题
这对于您的代码和用例来说并不是微不足道的,但这是可能的。@quamrana给出了一个如何实现的示例
您只需要通过
onscreenclick
将start
变量从temp
传递到temp2
在这里,我使用了一个
lambda
来组成一个新函数,它接受(x,y)
,但也转发给temp2
和start
:相关问题 更多 >
编程相关推荐