A Display Name
A Display Name

Reputation: 367

Hold key - Python Turtle

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

Upvotes: 2

Views: 7861

Answers (1)

cdlane
cdlane

Reputation: 41925

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.

Upvotes: 3

Related Questions