python中的计时

2024-10-02 22:31:24 发布

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

嗨,我想在python turtle中开个玩笑,它将测量从程序开始到用户点击空格的时间 我的代码是这样的,我在计算时间的时候遇到了问题

import turtle
import time

screen = turtle.Screen()
screen.setup(600,600)
t = turtle.Turtle('turtle')
t.speed(3)
time = time.time()

def prawy():
    t.setheading(0)
    t.fd(50)

def lewo():
    t.setheading(180)
    t.fd(50)

def gora():
    t.setheading(90)
    t.fd(50)

def dol():
    t.setheading(270)
    t.fd(50)

def spac(x):
    print(round(time.time()-x,2))


turtle.listen()

turtle.onkey(prawy, 'Right')
turtle.onkey(lewo, 'Left')
turtle.onkey(gora, 'Up')
turtle.onkey(dol, 'Down')
turtle.onkeypress(spac, 'space')

turtle.mainloop()

我知道我必须从一开始就把时间花在娱乐上,但我不知道怎么做 THX支持


Tags: import程序timedef时间screenturtlefd
3条回答

您可以使用一个守护进程线程,该线程遍历所有代码,并且您可以编写函数来打印空格键按下时的时间

线程:

import threading
import time
Score=0

def Start_Timer():
    global Score
    time.sleep(1)
    Score=Score+1
Timer=threading.Thread(target=Start_Timer, daemon=True)
Timer.start()

最后显示时间的代码:

def spac():
    print("{0}".format(Score))

将其与以前的代码结合使用:

import turtle
import time
import threading

Score=0

def Start_Timer():
    global Score
    time.sleep(1)
    Score=Score+1
Timer=threading.Thread(target=Start_Timer, daemon=True)
Timer.start()

def prawy():
    t.setheading(0)
    t.fd(50)

def lewo():
    t.setheading(180)
    t.fd(50)

def gora():
    t.setheading(90)
    t.fd(50)

def dol():
    t.setheading(270)
    t.fd(50)

def spac():
    print("{0}".format(Score))


turtle.listen()

turtle.onkey(prawy, 'Right')
turtle.onkey(lewo, 'Left')
turtle.onkey(gora, 'Up')
turtle.onkey(dol, 'Down')
turtle.onkeypress(spac, 'space')

turtle.mainloop()

还感谢Bialomazurcdlane事先提供的信息

这是我第一次回答其他问题,因此如果有任何错误,我真诚地道歉(我没有那么丰富的经验,这是我能做的最好的了。:p)

不能为事件处理程序定义任意参数。它们的参数签名是由turtle定义的,而不是由您定义的。因此,您需要减去包含时间开始的全局变量,而不是spac()的无效参数:

from turtle import Screen, Turtle
import time

def prawy():
    turtle.setheading(0)
    turtle.fd(50)

def lewo():
    turtle.setheading(180)
    turtle.fd(50)

def gora():
    turtle.setheading(90)
    turtle.fd(50)

def dol():
    turtle.setheading(270)
    turtle.fd(50)

def spac():
    print(round(time.time() - start, 2))

screen = Screen()
screen.setup(600, 600)

turtle = Turtle('turtle')
turtle.speed('slow')

screen.onkey(prawy, 'Right')
screen.onkey(lewo, 'Left')
screen.onkey(gora, 'Up')
screen.onkey(dol, 'Down')
screen.onkeypress(spac, 'space')

screen.listen()

start = time.time()

screen.mainloop()

据我所知,代码中没有声明名为x的变量

此外,您应该命名一个变量,就像导入的模块一样,从而更改 timet1的变量名

同时将spac(x)功能更改为:

def spac():
   global t1

   print(round(time.time()-t1,2))

保重

相关问题 更多 >