如何在定义函数/线程中创建计时器

2024-10-01 22:43:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试一个反应测试,问题是当我为定义函数中的时间定义一个变量时,它后来说变量布尔没有定义。我很想知道如何在定义函数中定义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

Tags: 函数inpy定义timeline时间start
3条回答

click(x,y)方法中有一行ms = end - a。变量end已在前一行中定义,但变量a未在代码中的任何位置定义。 这可能会给您带来错误

至于如何创建计时器,我认为您有一个作用域问题,我看到您在方法clicked()中创建并启动计时器,但是您想停止它并在方法click()中计算偏移量,最好的方法是在一个更大的类中,这些函数是方法,计时器是实例变量。但是,只需在这些函数之外使用全局变量,就可以获得相同的结果(尽管这可能不是很好的做法)

因此,每当在方法/函数内部定义变量时,就不能从该方法外部访问其值

这就是为什么当您试图访问start行中的total = end - start时,Python解释器不知道什么是start

有几种方法可以解决这个问题

  1. 将开始变量和结束变量移到方法外部(这些变量现在称为全局变量,而不是特定于方法的变量):
start = None
end = None
# Defining these variables outside the methods
# will allow you to access them from inside any method

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()
  1. 使用python类和对象为变量创建更具体的名称空间(这有点高级,但有助于保持代码更干净)
class Timer:
    def __init__():
        self.start = None
        self.end = None
    def temp(self, x, y):
        self.start = time.time()
        wn.onscreenclick(self.temp2)
    def temp2(self, x, y):
        self.end = time.time()
        print (self.end - self.start)

timer = Timer()

wn.onscreenclick(timer.temp)
  1. 将值作为参数传递给方法
start = None
end = None
# Defining these variables outside the methods
# will allow you to access them from inside any method

def temp(x, y):
    start = time.time()
    return start

def temp2(x, y, start):
    end = time.time()
    total = end - start
    print (total)

start = temp(x, y)
temp2(x, y, start)

这对于您的代码和用例来说并不是微不足道的,但这是可能的。@quamrana给出了一个如何实现的示例

您只需要通过onscreenclickstart变量从temp传递到temp2

在这里,我使用了一个lambda来组成一个新函数,它接受(x,y),但也转发给temp2start

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(lambda x,y: temp2(x,y,start))

def temp2(x, y, start):
    end = time.time()
    total = end - start
    print (time)

wn.onscreenclick(temp)
wn.mainloop()

相关问题 更多 >

    热门问题