直截了当,是否可以在python的Turtle中按下一个键并执行一段代码,例如:
当空间持续3秒时 - 空格()
如果需要,请输入以下代码:
import time
import sys
import turtle
width = 800
height = 600
turtle.screensize(width, height)
turtle.title('Youtube')
turtle.hideturtle()
turtle.penup()
def text(text, posx, posy, size):
turtle.pencolor('white')
turtle.goto(posx, posy)
turtle.write(text, font=("Arial", size, "normal"))
##ScreenRender
turtle.bgpic("background.gif")
turtle.hideturtle
#Text
text('Record A Video', -400, 225, 20)
text('Hold Space...', -345, 200, 15)
##End
turtle.done()
答案 0 :(得分:2)
是的,您可以将turtle.listen()
与其中一个turtle.onkey*()
例程结合使用。
如果需要,请输入以下代码:
import time
import turtle
WIDTH = 800
HEIGHT = 600
seconds = 0
def text(text, posx, posy, size):
turtle.pencolor('black')
turtle.goto(posx, posy)
turtle.write(text, font=("Arial", size, "normal"))
def press_space():
global seconds
seconds = time.time()
turtle.onkeypress(None, ' ')
def release_space():
if time.time() - seconds >= 3.0:
turtle.onkeyrelease(None, ' ')
text("thank you.", -200, 200, 15)
# ScreenRender
turtle.screensize(WIDTH, HEIGHT)
turtle.hideturtle()
turtle.penup()
# Text
text('Hold Space for 3 seconds...', -400, 200, 15)
# Event Handlers
turtle.listen()
turtle.onkeypress(press_space, ' ')
turtle.onkeyrelease(release_space, ' ')
# End
turtle.done()
保持时间可能不是直截了当的,因为键具有自己的重复频率。