2

Straight to the point, is it possible to hold a key down in python's Turtle and execute a piece of code, eg:

when space is held for 3 seconds - Space()

Here's the code if needed:

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()
cdlane
  • 40,441
  • 5
  • 32
  • 81
A Display Name
  • 367
  • 1
  • 9
  • 18

1 Answers1

3

Yes, you can use turtle.listen() in combination with one of the turtle.onkey*() routines.

Here's the code if needed:

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

The hold time may not be straightforward as keys have their own repeat frequency.

cdlane
  • 40,441
  • 5
  • 32
  • 81